【问题标题】:IF-sentence over all columns in a dataframe in RR中数据框中所有列的IF语句
【发布时间】:2020-09-28 10:18:53
【问题描述】:

我有一个 df,如果满足条件(如果列包含“你好吗”),我希望 R 在文本前面粘贴“嗨”。

t <- data.frame('x1' = c('how are you','whats up?', 'whats up?'), "x2" = c('how are you','how are you', 'whats up?'), "x3" = c('whats up?','how are you', 'whats up?'))

如何同时为所有列执行此操作? 我试过用 if 句和 ​​lapply


#this doesn't work

t[] <- if(t[] %like% ('how are you')) {paste("Hi, ",t[])}

t[] <- lapply(t, function(x)  if(x %like% ('how are you')) {paste("Hi,",x)})

#this works, but then all other content is erased;

t[] <- lapply(t, function(x) 
                ifelse(x %like% ('how are you'), paste("Hi,", x),""))

提前致谢!

【问题讨论】:

    标签: r dataframe if-statement conditional-statements lapply


    【解决方案1】:

    如果要进行模式匹配,可以使用grepl

    t[] <- lapply(t, function(x) ifelse(grepl('how are you', x), paste('Hi', x), x))
    

    或使用== 进行精确匹配。

    t[] <- lapply(t, function(x) ifelse(x == 'how are you', paste('Hi', x), x))
    t
    
    #              x1             x2             x3
    #1 Hi how are you Hi how are you      whats up?
    #2      whats up? Hi how are you Hi how are you
    #3      whats up?      whats up?      whats up?
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-17
      • 2015-12-16
      • 2021-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多