【发布时间】:2021-06-08 22:59:45
【问题描述】:
我有一个数据框和一个字符串。
我需要检查字符串中的元素是否在数据框的列名中。
如果不在数据框中,我需要创建一个新列,
如果它们在数据框中,则什么也不做
这是我的代表:
# dataframe
df <- data.frame(name = c("jon", "dan", "jim"),
age = c(44, 33, 33))
# string
st <- c("house", "car", "pet")
# for just one element in the string, this works
df %>%
mutate(house = if (exists('house', where = .)) house else "not there")
however, my function to apply to multiple elements is not working.. any help much appreciated..
make_missing_cols <- function(df, cols){
for(i in cols) {
df <- df %>%
mutate(cols[i] = if(exists(cols[i], where = df)) cols[i] else "not there")
}
return(df)
}
【问题讨论】:
-
那么对于给定的 df,您的预期输出是什么?
标签: r string dataframe dplyr data-manipulation