在数据帧内查找单元格并替换其值而无需循环R [英] Look for cell within a data frame and replace its value without loops R
问题描述
使用此df:
DF = data.frame(m=rep(1:2,2), y=rep(1998:1999,each=2), A=c(2:5), B=c(4,NA,6,7))
> DF
m y A B
1 1 1998 2 4
2 2 1998 3 NA
3 1 1999 4 6
4 2 1999 5 7
如何使用以下值作为坐标替换单个单元格:
How could I replace a single cell using as coordinates this values:
m = 2 ; y = 1999 ; col = 'A' ; val = 72
在这些值之后,我想用72代替5。
Following those values I want to replace 5 with 72.
编辑。
通过测试所有答案,我意识到我的问题非常基础,并不代表我问题。我尝试在没有for循环的情况下执行此操作,但失败了,最终使用了它。
Edit. As testing all the answers I realized my question is very basic and don't represent my problem. I tried to do it without for loops but failed and eventually used it.
因此,我想替换 DF $ c中的值$ c>数据帧,但使用其他数据帧:
So, I want to replace values within the DF
data frame but using this other data frame:
repl = data.frame(m=c(2,1), y=c(1999,1998), col=c('A','B'), val=c(72,100))
> repl
m y col val
1 2 1999 A 72
2 1 1998 B 100
这意味着 repl
数据帧的每一行都是要替换在 DF
中的值。
This means that each row of the repl
data frame is a value to replace in DF
.
我一直在尝试使用Psidom答案 mutate(A = replace(A,m == 2&y == 1999,72)
每行,但想知道是否可以不使用循环或不使用列名。
I've been trying to use Psidom answer mutate(A = replace(A, m == 2 & y == 1999, 72)
for each row but wonder if can be done without loops or without using column names.
谢谢。
推荐答案
dplyr
的方式是 mutant
+ if_else
:
DF %>% mutate(A = if_else(m == 2 & y == 1999, 72L, A))
# m y A B
#1 1 1998 2 4
#2 2 1998 3 NA
#3 1 1999 4 6
#4 2 1999 72 7
或变异
+ 替换
:
DF %>% mutate(A = replace(A, m == 2 & y == 1999, 72))
# m y A B
#1 1 1998 2 4
#2 2 1998 3 NA
#3 1 1999 4 6
#4 2 1999 72 7
根据条件返回一个替换为预期值的新向量。
which depending on the condition, returns a new vector with intended values replaced.
更新如果需要同时进行许多更新,则可以:
Update if you need to do many updates at the same time, you can:
1)重塑 DF
要更新的列集中在一个列中;
1) reshape DF
so the columns to be updated get gathered in a single column;
2)连接两个条件列 m
和 y
加上列标题列;
2) join on the two condition columns m
and y
plus the column headers column;
3)更新值;
4)重塑数据框back;
4) reshape the data frame back;
因此,与 tidyr
一起,您可以执行以下操作:
So together with tidyr
, you can do:
library(dplyr); library(tidyr)
DF %>%
gather(col, vals, -m, -y) %>%
left_join(repl, by = c("m", "y", "col")) %>%
mutate(vals = coalesce(val, vals)) %>%
select(-val) %>%
spread(col, vals)
# m y A B
#1 1 1998 2 100
#2 1 1999 4 6
#3 2 1998 3 NA
#4 2 1999 72 7
这篇关于在数据帧内查找单元格并替换其值而无需循环R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!