r - 在 R 中的字符串中不存在的数据框中创建列

标签 r string dataframe dplyr data-manipulation

我有一个数据框和一个字符串。
我需要检查字符串中的元素是否在数据框的列名中。
如果不在数据框中,我需要创建一个新列,
如果它们在数据框中,则什么也不做

这是我的代表:

# 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/

相关文章:

java - 将非数字字符串转换为整数?

r - 将一个字符串分解成不同行的多个字符串

swift - 有什么方法可以替换 Swift String 上的字符吗?

r - 如何打造临床环境洁净?

r - 将列添加到数据框以显示最新的描述

r - 如何仅在R中调整y轴标签的大小?

javascript - 使用 jQuery 获取 onclick 字符串

python - 如何同时将函数与 if 语句应用于多个数据帧列

python - 将函数应用于 pandas Python 中的每一行时出现数据转换错误

r - 使用sparklyr::spark_read_json时添加文件名