【问题标题】:ddply/transform does not apply function to each element of a character vectorddply/transform 不对字符向量的每个元素应用函数
【发布时间】:2015-11-24 16:14:43
【问题描述】:

我有一个数据框,我想使用我编写的名为“group1”的函数来转换第一列:

group1 <- function(x) {
  temp <- strsplit(x,"_")[[1]][2]
  temp <- gsub("Yellow", "", temp)
  temp <- gsub("Blue", "", temp)
  as.numeric(temp)
}

例如,将此函数应用于字符串“MHY_Blue23_Yellow16_11A”应该会产生结果 23。当输入只是一个字符串时确实会发生这种情况,但是当我尝试将此函数应用于字符向量时,出现了问题.我尝试使用“变换”使其适用于向量中的每个元素:

data_ling_RT2 <- transform(data_ling_RT, Group1 = group1(Code_Trials)))

但是,我没有得到一个名为“Group1”的新列依赖于“Code_Trials”中的相应元素的数据框,而是得到“Group1”中的所有元素仅基于“Code_Trials”的第一个元素”。我想这与我写“group1”的方式有关,但我找不到我做错了什么。 使用 ddply 更糟糕 - 有时我什至在“Group1”列中什么都没有......

非常感谢您的帮助!

【问题讨论】:

    标签: r dataframe character transform plyr


    【解决方案1】:

    我们只使用[[1]] 选择第一个list 元素。因此,当我们使用transform 时,第一个被修改的元素会循环到长度。

    我们可以通过在执行gsub 之前使用sapply 提取每个list 元素的元素元素来更改group1 函数。目前尚不清楚为什么我们要替换“黄色”,因为第二个元素似乎只有“蓝色”。

     group1 <- function(x) {
       temp <- strsplit(x,"_")
       temp <- sapply(temp, '[', 2) 
       temp <- gsub("Yellow", "", temp)
       temp <- gsub("Blue", "", temp)
       as.numeric(temp)
     }
    

    上面的代码可以简化为

     group2 <- function(x) {
         temp <- strsplit(x,"_")
          temp <- sapply(temp, '[', 2) 
          temp <- as.numeric(gsub('\\D+', '', temp))
        }
    

    使用可重现的示例

     data_ling_RT <- data.frame(Code_Trials= c("MHY_Blue23_Yellow16_11A" , 
           "MHY_Blue24_Yellow16_11A"), stringsAsFactors=FALSE)
     transform(data_ling_RT, Group1 = group1(Code_Trials))
     #              Code_Trials Group1
     #1 MHY_Blue23_Yellow16_11A     23
     #2 MHY_Blue24_Yellow16_11A     24
    

    【讨论】:

    • 谢谢,阿克伦!有效。所以我的谬误是我有一个列表,而 ddply 和 transform 并不是要在列表元素上工作,而是在数据框上工作。正确的?那我可以让它与 llply 一起工作吗?另外,您能否解释一下sapply(temp,'[', 2) 中的第二个参数? gsub('\\D+', '', temp) 中的第一个参数呢?非常感谢。 PS - 该函数同时包含“黄色”和“蓝色”,因为输入有时在其第二个参数中有“蓝色”,有时有“黄色”。
    • 谢谢@akrun,我不知道你可以在 *apply 中使用 '[' 或 '[[' 作为函数。这真的很有帮助!
    猜你喜欢
    • 1970-01-01
    • 2013-08-28
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    相关资源
    最近更新 更多