我有一个数据框和一个字符串。
我需要检查字符串中的元素是否在数据框的列名中。
如果不在数据框中,我需要创建一个新列,
如果它们在数据框中,则什么也不做
这是我的代表:
# 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)
}
最佳答案
在函数中,我们需要一个赋值运算符作为:=
和求值(!!
)
make_missing_cols <- function(df, cols){
for(i in seq_along(cols) ){
df <- df %>%
mutate(!!cols[i] := if(exists(cols[i],
where = df)) cols[i] else "not there")
}
return(df)
}
-测试
make_missing_cols(df, st)
# name age house car pet
#1 jon 44 not there not there not there
#2 dan 33 not there not there not there
#3 jim 33 not there not there not there
关于r - 在 R 中的字符串中不存在的数据框中创建列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66574270/