【问题标题】:Add prefix and suffix to list values R添加前缀和后缀以列出值 R
【发布时间】:2017-04-20 19:21:15
【问题描述】:

我的 R 代码

data <- read.csv('filename.csv')
typof(data)
[1] "list"

str(data)
    'data frame' : 9 obs. of 10 variables
    $Name: Factor w/9 levels "Name 1", "Name 2",....
    $Column2: chr "","Text1","","Text2"
    $Column3: chr "Text2","Text3","","Text1"
    $Column4: chr "","","","Text1"
#and so on

要求:

我想要的只是$Column2$Column3$Column4,...只要有非空白值,添加前缀(Here this is)和后缀(completed)。 所以考虑到上面的data Column2,第二行现在有值"Text1"应该变成"Here this is Text1 completed."

Column3: 1st, 2nd and 4th cell 中同样需要添加前缀和后缀值。

不想使用循环,除非需要/必要。

我的尝试:

我尝试了一些尝试,例如interactionmgetappend 等等,但似乎没有任何效果。

【问题讨论】:

  • 你试过mutate_eachpaste吗?
  • 看我的回答,它在一行代码中完成,它也经过测试。
  • @ZeeshanArif 您的答案针对单个列,而不是整个数据集。此外,已经发布了类似的答案(也在列上循环)

标签: r


【解决方案1】:

我会将其矢量化如下

indx <- which(data[, -1] != "", arr.ind = TRUE) # Find all non-empty incidences 
data[, -1][indx] <- paste("Here this is", data[, -1][indx], "completed.")

【讨论】:

  • indx 也考虑了第 1 列,我不想在其中应用条件。我该如何更改?
【解决方案2】:

这将适用于前 4 列

apply(data[,2:4],2,function(x) ifelse(x != "",paste("Here this is ",x," completed."),x))

假设每列的前缀和后缀相同。它确实返回一个矩阵,但很容易将其转换为数据帧。 希望对您有所帮助。

编辑:刚刚意识到您的数据在列表中,因此您需要lapplysapply。比如:

sapply(data,function(x) ifelse(x != "",paste("Here this is ",x," completed."),x))[,2:4]

还返回一个矩阵。

【讨论】:

    【解决方案3】:

    这是一个带有set 的选项,它可以在没有任何复制的情况下就地分配

    library(data.table)
    setDT(data)
    for(j in 2:ncol(data)){
          set(data, i = which(data[[j]]!=""), 
                    j = j,
                    value = paste("Here there is ",  data[[j]][data[[j]]!=""], " completed."))
        }
    data
    #     Name                          Column2                          Column3
    #1: Name 1                                  Here there is  Text1  completed.
    #2: Name 2 Here there is  Text1  completed.                                 
    #3: Name 3 Here there is  Text2  completed. Here there is  Text2  completed.
    #4: Name 4                                  Here there is  Text3  completed.
    

    数据

    data <- structure(list(Name = structure(1:4, .Label = c("Name 1", "Name 2", 
    "Name 3", "Name 4"), class = "factor"), Column2 = c("", "Text1", 
     "Text2", ""), Column3 = c("Text1", "", "Text2", "Text3")), .Names = c("Name", 
     "Column2", "Column3"), row.names = c(NA, -4L), class = "data.frame")
    

    【讨论】:

      【解决方案4】:

      使用lapply函数(也是一个循环):

      # dummy data
      df1 <- mtcars[1:5, 1:3]
      # add blanks
      df1[2,2] <- ""
      df1
      #                    mpg cyl disp
      # Mazda RX4         21.0   6  160
      # Mazda RX4 Wag     21.0      160
      # Datsun 710        22.8   4  108
      # Hornet 4 Drive    21.4   6  258
      # Hornet Sportabout 18.7   8  360
      
      # add prefix and suffix
      res <- cbind(df1[, 1, drop = FALSE],
                   data.frame(
                     lapply(df1[, -1], function(i)
                       ifelse(i == "", i, paste("Here this is", i, "completed.")))))
      
      
      res
      #                    mpg                       cyl                        disp
      # Mazda RX4         21.0 Here this is 6 completed. Here this is 160 completed.
      # Mazda RX4 Wag     21.0                           Here this is 160 completed.
      # Datsun 710        22.8 Here this is 4 completed. Here this is 108 completed.
      # Hornet 4 Drive    21.4 Here this is 6 completed. Here this is 258 completed.
      # Hornet Sportabout 18.7 Here this is 8 completed. Here this is 360 completed.
      

      【讨论】:

      • @DavidArenburg 我更喜欢保持输入数据完整。如果他们想要覆盖输入数据或保留为单独的新数据帧,则取决于 OP。
      【解决方案5】:
      DF = transform(ifelse(data$Column2 == "", data$Column2, sprintf('Here it is %s completed', data$Column2)))
      DF <- data.frame (DF, data$Name, data$Column3)
      

      【讨论】:

      • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要用解释性的 cmets 挤满你的代码,这会降低代码和解释的可读性!
      • 这应该在多个列中完成,而不是特定的列
      • 你明白了,不知道哪个功能...从来没有做过 R...哪个功能如何扩展?
      猜你喜欢
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      • 1970-01-01
      • 2015-08-02
      • 1970-01-01
      • 1970-01-01
      • 2016-03-07
      相关资源
      最近更新 更多