我希望将一个数据帧的值作为列名附加到另一个数据帧。
如果我“手动”分配索引值,我编写的代码将每次生成一个列:
df_searchtable <- data.frame(category = c("air", "ground", "ground", "air"), wiggy = c("soar", "trot", "dive", "gallop"))
df_host <- data.frame(textcolum = c("run on the ground", "fly through the air"))
#create vector of categories
categroups <- as.character(unique(df_searchtable$category))
##### if I assign colum names one at a time using index numbers no prob:
group = categroups[1]
df_host[, group] <- NA
##### if I use a loop to assign the column names:
for (i in categroups) {
group = categroups[i]
df_host[, group] <- NA
}代码失败,给出:
Error in [<-.data.frame(`*tmp*`, , group, value = NA) :
missing values are not allowed in subscripted assignments of data frames我怎样才能解决这个问题?
发布于 2019-07-24 02:14:52
下面是一个简单的基本R解决方案:
df_host[categroups] <- NA
df_host
textcolum air ground
1 run on the ground NA NA
2 fly through the air NA NA循环的问题在于,您正在循环每个元素,而您的代码则假设您正在循环通过1, 2, ..., n。
例如:
for (i in categroups) {
print(i)
print(categroups[i])
}
[1] "air"
[1] NA
[1] "ground"
[1] NA要修复循环,您可以做两件事中的一件:
for (group in categroups) {
df_host[, group] <- NA
}
# or
for (i in seq_along(categroups)) {
group <- categroups[i]
df_host[, group] <- NA
}发布于 2019-07-24 00:35:24
这里有一个使用map的解决方案。
bind_cols(df_host,
map_dfc(categroups,
function(group) tibble(!!group := rep(NA_real_, nrow(df_host)))))给予:
textcolum air ground
1 run on the ground NA NA
2 fly through the air NA NAmap_dfc映射到输入categroups上,为每个输入categroups创建一个单列tibble,并将新创建的tibbles连接到一个dataframe中。bind_cols将原始数据加入到新的tibble中。或者,您可以使用walk
walk(categroups, function(group){df_host <<- mutate(df_host, !!group := rep(NA_real_, nrow(df_host)))})发布于 2019-07-24 00:41:17
下面是一个丑陋的基本R解决方案:创建一个带有列名的空矩阵,并将其cbind到第二个dataframe。
df_searchtable <- data.frame(category = c("air", "ground", "ground", "air"),
wiggy = c("soar", "trot", "dive", "gallop"),
stringsAsFactors = FALSE)
df_host <- data.frame(textcolum = c("run on the ground", "fly through the air"),
stringsAsFactors = FALSE)
cbind(df_host,
matrix(nrow = nrow(df_host),
ncol = length(unique(df_searchtable$category)),
dimnames = list(NULL, unique(df_searchtable$category))))结果:
textcolum air ground
1 run on the ground NA NA
2 fly through the air NA NAhttps://stackoverflow.com/questions/57173657
复制相似问题