使用下面的示例数据框,我正在寻找一种方法,从列v2开始向右移动值,同时用零替换空白,如果列v9包含&#39; a&#39;。< / p>
set.seed(0)
df <- matrix(sample(c("a", 1:3), 100, replace = TRUE), nrow=10)
colnames(df) <- c(paste0("v", 1:10))
df <- as_tibble(df)
df$v11 <- 0
# A tibble: 10 x 11
v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11
<chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <dbl>
1 3 a 3 1 1 2 1 3 3 a 0
2 1 a 3 1 3 1 3 1 1 a 0
3 1 a a 2 2 3 1 3 2 a 0
4 2 2 2 1 3 1 1 1 1 2 0
5 3 1 a a 2 a 1 1 1 3 0
6 a 3 1 3 2 a 2 1 3 3 0
7 3 1 1 2 3 a 1 3 a 3 0
8 3 2 a 3 a 1 1 3 2 1 0
9 2 3 1 a 1 2 3 1 a 1 0
10 2 1 3 2 2 2 a 3 a 3 0
所以结果数据帧将是(第7,9,10行移位):
v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11
1 3 a 3 1 1 2 1 3 3 a 0
2 1 a 3 1 3 1 3 1 1 a 0
3 1 a a 2 2 3 1 3 2 a 0
4 2 2 2 1 3 1 1 1 1 2 0
5 3 1 a a 2 a 1 1 1 3 0
6 a 3 1 3 2 a 2 1 3 3 0
7 3 0 1 1 2 3 a 1 3 a 3
8 3 2 a 3 a 1 1 3 2 1 0
9 2 0 3 1 a 1 2 3 1 a 1
10 2 0 1 3 2 2 2 a 3 a 3
答案 0 :(得分:3)
首先,获取v9
列包含'a'的所有行。
req_rows <- which(df$v9 == "a")
req_rows
[1] 7 9 10
第二次,将细胞移位到所需位置
df[req_rows,2:length(df)] <- df[req_rows,1:length(df)-1]
> df
# A tibble: 10 × 11
v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11
<chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 3 a 3 1 1 2 1 3 3 a 0
2 1 a 3 1 3 1 3 1 1 a 0
3 1 a a 2 2 3 1 3 2 a 0
4 2 2 2 1 3 1 1 1 1 2 0
5 3 1 a a 2 a 1 1 1 3 0
6 a 3 1 3 2 a 2 1 3 3 0
7 3 3 1 1 2 3 a 1 3 a 3
8 3 2 a 3 a 1 1 3 2 1 0
9 2 2 3 1 a 1 2 3 1 a 1
10 2 2 1 3 2 2 2 a 3 a 3
第三次,用零替换空白。
df$v2[req_rows] <- 0
导致
> df
# A tibble: 10 × 11
v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11
<chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 3 a 3 1 1 2 1 3 3 a 0
2 1 a 3 1 3 1 3 1 1 a 0
3 1 a a 2 2 3 1 3 2 a 0
4 2 2 2 1 3 1 1 1 1 2 0
5 3 1 a a 2 a 1 1 1 3 0
6 a 3 1 3 2 a 2 1 3 3 0
7 3 0 1 1 2 3 a 1 3 a 3
8 3 2 a 3 a 1 1 3 2 1 0
9 2 0 3 1 a 1 2 3 1 a 1
10 2 0 1 3 2 2 2 a 3 a 3
答案 1 :(得分:1)
df[df$v9=='a',paste('v',2:11,sep = "")] <-
df%>%
select(v2:v11)%>%
filter(v9=='a')%>%
t()%>%
lag(default = 0)%>%
t()%>%
as_tibble()