[英]replace a value in df based on next one R
I have a df like this我有一个这样的df
missing_1 missing_4 missing_5
1: 7dzx
2: 7dzxALA1085 ALA 1085
3: 7dzxALA1085ALA1085 ALA 1085
4: 7dzx
5: 7dzxALA156 ALA 156
6: 7dzxALA156ALA156 ALA 156
and when missing_4 and missing_5 are empty I would like to replace that values with the folowing ones in that column.当 missing_4 和 missing_5 为空时,我想用该列中的以下值替换该值。 So it should become:
所以它应该变成:
missing_1 missing_4 missing_5
1: 7dzx ALA 1085
2: 7dzxALA1085 ALA 1085
3: 7dzxALA1085ALA1085 ALA 1085
4: 7dzx ALA 156
5: 7dzxALA156 ALA 156
6: 7dzxALA156ALA156 ALA 156
I was thinking about a for loop but I'm not skilled enought to realize it.我正在考虑一个 for 循环,但我没有足够的技能来实现它。 Thanks!
谢谢!
We could use fill
from tidyr
我们可以使用
tidyr
的fill
library(dplyr)
library(tidyr)
df1 %>%
fill(c(missing_4, missing_5), .direction = "updown")
-output -输出
missing_1 missing_4 missing_5
1: 7dzx ALA 1085
2: 7dzxALA1085 ALA 1085
3: 7dzxALA1085ALA1085 ALA 1085
4: 7dzx ALA 156
5: 7dzxALA156 ALA 156
6: 7dzxALA156ALA156 ALA 156
df1 <- structure(list(missing_1 = c("7dzx", "7dzxALA1085", "7dzxALA1085ALA1085",
"7dzx", "7dzxALA156", "7dzxALA156ALA156"), missing_4 = c(NA,
"ALA", "ALA", NA, "ALA", "ALA"), missing_5 = c(NA, 1085L, 1085L,
NA, 156L, 156L)), class = c("data.table", "data.frame"), row.names = c(NA,
-6L)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.