用R重新排列第一行的行

时间:2016-02-23 15:45:38

标签: r row na

我有这样的数据框,

user_name1     user_name2        user_name3
0                Alex              0
0                  0               0
0                  0             Jacob
0
                  Lee             Mark
John               0              Kevin

我想以这种方式重新排列,忽略0或任何NA值,

user_name1     user_name2        user_name3
    John          Alex              Jacob
    0             Lee                Mark
    0              0                 Kevin
    0              0                   0
    0              0                   0
    0              0                   0

值得注意的是,行号将保持不变。

user_name1 <- c(0,0,0,0, "", "John")
user_name2 <- c("Alex", 0,0, "", "Lee",0)
user_name3 <- c(0,0, "Jacob", "",  "Mark", "Kevin")
df<- data.frame(user_name1, user_name2, user_name3)

2 个答案:

答案 0 :(得分:3)

递减sort效果很好:

df[] <- lapply(df, sort, decreasing=TRUE)
df
#  user_name1 user_name2 user_name3
#1       John        Lee       Mark
#2          0       Alex      Kevin
#3          0          0      Jacob
#4          0          0          0
#5          0          0          0

<强>更新

如果数据中有NA个值的空格,您可以先修复它们,然后运行上面的代码:

#Example with NA and blank ""
  user_name1 user_name2 user_name3
1          0       Alex          0
2          0          0          0
3          0          0      Jacob
4          0                  <NA>
5                   Lee       Mark
6       John          0      Kevin

首先将值强制为零,然后sort

df[df=="" | is.na(df)] <- 0
df[] <- lapply(df, sort, decreasing=TRUE)
#  user_name1 user_name2 user_name3
#1       John        Lee       Mark
#2          0       Alex      Kevin
#3          0          0      Jacob
#4          0          0          0
#5          0          0          0
#6          0          0          0

数据

user_name1 <- c(0,0,0,0,"", "John")
user_name2 <- c("Alex", 0,0,"", "Lee",0)
user_name3 <- c(0,0, "Jacob", NA, "Mark", "Kevin")
df<- data.frame(user_name1, user_name2, user_name3,
                      stringsAsFactors=FALSE)

答案 1 :(得分:2)

使用dplyr

library(dplyr)
df[df=="" | is.na(df)] <- 0
df <- df %>% mutate_each(funs(sort(.,decreasing = TRUE))) 

#      user_name1 user_name2 user_name3
#1       John        Lee       Mark
#2          0       Alex      Kevin
#3          0          0      Jacob
#4          0          0          0
#5          0          0          0