我有一个看起来有点像下面的数据框。 A1U_sweet 实际上是真实数据帧中的第 19 列,C1U_sweet 是真实数据帧中的第 39 列。有 20 个以 A## 开头的列和 20 个以 C## 开头的列。
A1U_sweet A2F_dip A3U_bbq C1U_sweet C2F_dip C3U_bbq
1 2 1 NA NA NA
NA NA NA 4 1 2
2 4 7 NA NA NA
我想制作结合 A 值和 C 值的附加列。生成的数据框将包括类似于 B1U_sweet 和 B2F_dip 的列。
A1U_sweet A2F_dip A3U_bbq C1U_sweet C2F_dip C3U_bbq B1U_sweet B2F_dip
1 2 1 NA NA NA 1 2
NA NA NA 4 1 2 4 1
2 4 7 NA NA NA 2 4
有人建议我尝试以下代码。前两行有效,但在实现其余部分后,我收到一条错误消息。
types <- grep('^A([0-9]|[12][0-9])[A-Z]_[a-z]+', names(df)) ## Get all "A"
patterns
types <- substr(types, 2, Inf) ## Remove the "A"
for (tp in types) {
aa <- df[[paste0('A', tp)]] ## "A" column
cc <- df[[paste0('C', tp)]] ## "C" column
df[[paste0('B', tp)]] <- ifelse(is.na(aa), aa, cc)
}
这是错误消息:
Error in `[[<-.data.frame`(`*tmp*`, paste0("B", tp), value = logical(0)) :
replacement has 0 rows, data has 94
In addition: Warning message:
In is.na(aa) : is.na() applied to non-(list or vector) of type 'NULL'
数据确实有 94 列,但我不明白为什么这可能会触发此错误。如果您能帮助使该代码正常运行,我将不胜感激!
编辑:这就是我到目前为止一直在做的事情。我必须进入并手动更改我想要组合的每组列的列名称。一定有更好的方法!
df$B1U_sweetnsour<-A1U_sweetnsour
df$B1U_sweetnsour[is.na(df$B1U_sweetnsour)]<- C1U_sweetnsour[is.na(A1U_sweetnsour)]