【问题标题】:create columns in dataframe with absent from string in R在数据框中创建列,而 R 中的字符串不存在
【发布时间】: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


【解决方案1】:

在函数中,我们需要一个赋值运算符 := 和评估 (!!)

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

【讨论】:

  • 这很好用,可以接受-我仍然对赋值运算符感到迷茫-它是如何工作的?我不会想出来的!
  • @mdb_ftl 通常的赋值=lhs 上的未加引号的值按字面意思分配,即cols[i] 按字面意思作为列名而不是评估。所以,我们需要:=。或者也可以在mutate 步骤之后使用= 使用临时列名,然后在之后使用rename 来执行此操作
【解决方案2】:

一个不同的选项可能是:

df %>%
 add_column(!!!setNames(rep("not there", length(setdiff(st, names(.)))), setdiff(st, names(.))))

 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

【讨论】:

    【解决方案3】:

    您可以在基础 R 中使用 setdiff

    make_missing_cols <- function(df, cols){
      df[setdiff(cols, names(df))] <- 'not there'
      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
    
    make_missing_cols(df, c('house', 'name'))
    #  name age     house
    #1  jon  44 not there
    #2  dan  33 not there
    #3  jim  33 not there
    
    make_missing_cols(df, 'name')
    
    #  name age
    #1  jon  44
    #2  dan  33
    #3  jim  33
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 2016-10-22
      相关资源
      最近更新 更多