【发布时间】:2020-05-26 03:03:57
【问题描述】:
我有以下任务:用数据帧 B 中相同变量的值替换数据帧 A 中变量 V1 的值。接下来我模拟数据帧:
set.seed(123)
A<-data.frame(id1=sample(1:10,10),id2=sample(1:10,10),V1=rnorm(10),V2=rnorm(10))
###create dataframe B
B<-A[sample(1:10,5),1:3]
###change values to be updated in df A
B$V1<-rnorm(5)
###create a row which is not in A, to make it more interesting
B<-rbind(B,c(11,12,rnorm(1)))
现在我提供一个非最佳解决方案,我希望它更清洁
temp<-left_join(A,B,by=c("id1","id2"))
temp[!is.na(temp$V1.y),"V1.x"]<-temp[!is.na(temp$V1.y),"V1.y"]
A<-temp[,setdiff(colnames(temp),"V1.y")]
colnames(A)[colnames(A) %in% "V1.x"]<-"V1"
最好避免创建临时对象并直接修改 df A。此外,该解决方案应该是可扩展的,以替换 A 的多列中的值。我认为类似于
A[expression1,desired_cols]<-B[expression2,desired_cols]
其中expression1 和expression2 用于匹配df 中的索引,desired_cols 是要替换的列的名称
【问题讨论】:
标签: r dataframe indexing replace