我试图实现类似于this和this问题的类似问题,但不是用单个值替换,而是基于另一列替换。R:用另一列中的值替换多列数据帧中的多个值
的数据是从具有特定的网站“是”的时候被采取的具体日期测量,我现在想的河上的那些特定日期的水位。我的数据看起来是这样的(但有更多的地点和日期):
date <- c('2000-01-01','2000-01-02','2000-01-03','2000-01-04','2000-01-05','2000-01-06','2000-01-07','2000-01-08','2000-01-09','2000-01-10')
date <- as.Date(date)
Site1 <- c('yes','','yes','','yes','','yes','','','')
Site2 <- c('yes','yes','yes','','','','','yes','','yes')
Site3 <- c('','','','','','','yes','yes','','yes')
waterlevel <- c(24,58,2,38,18,59,20,98,16,88)
df <- data.frame(date,Site1,Site2,Site3,waterlevel)
这给出了这样的数据帧:
date Site1 Site2 Site3 waterlevel
1 2000-01-01 yes yes 24
2 2000-01-02 yes 58
3 2000-01-03 yes yes 2
4 2000-01-04 38
5 2000-01-05 yes 18
6 2000-01-06 59
7 2000-01-07 yes yes 20
8 2000-01-08 yes yes 98
9 2000-01-09 16
10 2000-01-10 yes yes 88
,我想输出数据框,看起来像这样:
date Site1 Site2 Site3 waterlevel
1 2000-01-01 24 24 24
2 2000-01-02 58 58
3 2000-01-03 2 2 2
4 2000-01-04 38
5 2000-01-05 18 18
6 2000-01-06 59
7 2000-01-07 20 20 20
8 2000-01-08 98 98 98
9 2000-01-09 16
10 2000-01-10 88 88 88
我已经尝试使用上述问题的解决方案代码与一个不同的数据框中的水位匹配参数,但解决方案没有工作:
sel <- grepl("Site",names(df))
df[sel] <- lapply(df[sel], function(x) replace(x,x %in% 2:4, df2$waterlevel[match(df$date,df2$date)]))
任何帮助将非常感激。
@PierreLafortune为什么你想将这些列到类'character'? – Roland
但是NA更有意义。 –