将数据帧转换为r中的范围标签

时间:2014-11-25 05:55:58

标签: r loops

我有一个看起来像这样的数据框。

df <- data.frame(Var1=c(1:10))

   Var1
    1
    2
    3
    4
    5
    6
    7
    8
    9
   10

我想将上面的数据框转换为范围标签,例如:&#34; 1及以下&#34;,&#34; 1到2&#34;,&#34; 3到4&#34 ;依此类推,直到&#34; 10及以上&#34;。所以我在下面创建了这个循环:

rangelist <- function(i){
  start=paste( df$Var1[1],"and below")
  middle=paste( df$Var1[i+1],"to", df$Var1[i+2])
  last=paste(df$Var1[nrow(df)],"and above") 


  paste(start)
  paste(middle)
  paste(last)

}



sapply(1:nrow(df),rangelist)

但上面的循环让我回答:

[1] "10 and above" "10 and above" "10 and above" "10 and above" "10 and above" "10 and above"
 [7] "10 and above" "10 and above" "10 and above" "10 and above"

1 个答案:

答案 0 :(得分:1)

尝试

indx <- df$Var1[-c(1, nrow(df))]
df$label <-  c('1 and below', paste(indx-1, indx, sep=' to '), '10 and above')
df$label
 #[1] "1 and below"  "1 to 2"       "2 to 3"       "3 to 4"       "4 to 5"      
 #[6] "5 to 6"       "6 to 7"       "7 to 8"       "8 to 9"       "10 and above"

更新

更通用的是

 indx <- setdiff(1:nrow(df), c(1, nrow(df)))
 with(df, c(paste(Var1[1], 'and below'), sprintf('%s to %s', Var1[indx-1],
              Var1[indx]), paste(Var1[nrow(df)], 'and above')))
 #[1] "1 and below"  "1 to 2"       "2 to 3"       "3 to 4"       "4 to 5"      
 #[6] "5 to 6"       "6 to 7"       "7 to 8"       "8 to 9"       "10 and above"
相关问题