我有这样的数据框,
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)
答案 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