代码之家  ›  专栏  ›  技术社区  ›  PaulHurleyuk

有没有更好的(即矢量化)方法将列名的一部分放入R中数据帧的行中

  •  3
  • PaulHurleyuk  · 技术社区  · 16 年前

    我在R中有一个数据帧,它来自于对熔化/浇铸操作的结果运行一些统计数据。我想在这个数据帧中添加一行,其中包含一个标称值。该标称值出现在每列的名称中

    df<-as.data.frame(cbind(x=c(1,2,3,4,5),`Var A_100`=c(5,4,3,2,1),`Var B_5`=c(9,8,7,6,5)))
    > df
      x Var A_100 Var B_5
    1 1         5       9
    2 2         4       8
    3 3         3       7
    4 4         2       6
    5 5         1       5
    

    所以,我想创建一个新行,它在Var a\u 100列中包含'100',在Var B\u 5列中包含'5'。目前这是我正在做的,但我相信一定有更好的,矢量化的方法来做到这一点。

    temp_nom<-NULL
    for (l in 1:length(names(df))){
     temp_nom[l]<-strsplit(names(df),"_")[[l]][2]
     }
    temp_nom
    [1] NA    "100" "5"  
    df[6,]<-temp_nom
    > df
         x Var A_100 Var B_5
    1    1         5       9
    2    2         4       8
    3    3         3       7
    4    4         2       6
    5    5         1       5
    6 <NA>       100       5
    rm(temp_nom)
    

    1 回复  |  直到 16 年前
        1
  •  1
  •   Marek    16 年前

    您可以创建 temp_nom

    # strsplit create list so you can sapply on it
    sapply(strsplit(names(df),"_"), "[", 2)
    
    # using regular expressions:
    sub(".+_|[^_]+", "", names(df))
    

    你可以转化为 标称温度

    df[nrow(df)+1,] <- as.numeric(temp_nom)
    

    当然,你可以用一行字:

    df[nrow(df)+1,] <- as.numeric(sapply(strsplit(names(df),"_"), "[", 2))
    # or
    df[nrow(df)+1,] <- as.numeric(sub(".+_|[^_]+", "", names(df)))