[英]R: Trying to replace values in one column with values in another column based on some conditions
So I have aa dataframe,df: df = data.frame(c("",1,1),c(1,"",1),c(1,1,""))
所以我有一个 dataframe,df:
df = data.frame(c("",1,1),c(1,"",1),c(1,1,""))
I want to loop through the dataframe and replace the values in the first and second column, if they are empty, with the value in the third column if it has a value in it:我想遍历 dataframe 并将第一列和第二列中的值(如果它们为空)替换为第三列中的值(如果其中有值):
n = nrow(df)
for(i in 1:n)df[i,] <-{
if(df[i,1] == "" & df[i,2] == "" & df[i,3] != ""){
df[i,1] = df[i,3]
df[i,2] = df[i,3]
}
}
However, I get the following error:但是,我收到以下错误:
error in x[[jj]][iseq] <- vjj: replacement has length zero.
I've been trying for quite some time, but can't figure our what I'm doing wrong.我已经尝试了很长一段时间,但无法弄清楚我做错了什么。 Any help would be much appreciated.
任何帮助将非常感激。
Since R is vectorized you do not need a loop:由于 R 是矢量化的,因此您不需要循环:
df <- structure(list(A = c("1", "1", "1"), B = c("1", "1", "1"), C = c("1",
"1", "")), row.names = c(NA, -3L), class = "data.frame")
Note your data are character vectors as in your example data.请注意,您的数据是示例数据中的字符向量。 The answer will differ slightly if they are numeric.
如果它们是数字,答案会略有不同。
df$A[df$A==""] <- df$C[df$A==""]
df$B[df$B==""] <- df$C[df$B==""]
df
# A B C
# 1 1 1 1
# 2 1 1 1
# 3 1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.