问题描述
我有一个5列的数据框:4列具有值,而1列为空.我想用4个列中任何一个的任何值填充空列.
I have a data frame of 5 columns: 4 columns have values and the 1 column that is empty. I want to fill the empty column with any value from any of the 4 columns.
假设这是我的数据框df
:
Col1 Col2 Col3 Col4 Col5
11 11
2 2 2
23
4 4
15 15
我希望我的结果看起来像这样:
I want my result to look like this:
Col1 Col2 Col3 Col4 Col5
11 11 11
2 2 2 2
23 23
4 4 4
15 15 15
编辑,我应用了每个人提供的答案,但是由于某些原因,它仍然无法正常工作.如果有帮助,这是我的实际数据中的dput(head(df))
:
EDIT I applied the answers provided by everyone, but it still isn't working for some reason. If it helps, this is the dput(head(df))
of my actual data:
structure(list(Treat_One = c(" ", "5 2012", "4 2008", "4 2010",
" ", "2 2008"), Treat_Two = c("8 2010", "5 2012", "4 2008",
"4 2010", "8 2011", "2 2008"), Treat_Three = c(" ", "5 2012",
"4 2008", "4 2010", "8 2011", "2 2008"), Treat_Four = c(" ",
" ", " ", " ", " ", " ")), .Names = c("Treat_One",
"Treat_Two", "Treat_Three", "Treat_Four"), row.names = c(NA,
6L), class = "data.frame")
编辑包含的str(df)
'data.frame': 209 obs. of 4 variables:
$ Treat_One : chr " " "5 2012" "4 2008" "4 2010" ...
$ Treat_Two : chr "8 2010" "5 2012" "4 2008" "4 2010" ...
$ Treat_Three: chr " " "5 2012" "4 2008" "4 2010" ...
$ Treat_Four : chr " " " " " " " " ...
推荐答案
基于OP提供的新数据,我们可以使用trimws
Based on the new data provided by the OP we can remove leading/trailing white spaces with trimws
df$Treat_Four <- apply(df, 1, function(x) sample(x[trimws(x) != ""], 1))
df
# Treat_One Treat_Two Treat_Three Treat_Four
#1 8 2010 8 2010
#2 5 2012 5 2012 5 2012 5 2012
#3 4 2008 4 2008 4 2008 4 2008
#4 4 2010 4 2010 4 2010 4 2010
#5 8 2011 8 2011 8 2011
#6 2 2008 2 2008 2 2008 2 2008
原始答案
我们可以逐行使用apply
并取不等于空字符串的元素中的1 sample
We can use apply
row-wise and take 1 sample
of the element which is not equal to empty string
df$Col5 <- apply(df, 1, function(x) sample(x[x != ""], 1))
df
# Col1 Col2 Col3 Col4 Col5
#1 1 1 1
#2 2 2 2 2
#3 3 3
#4 4 4 4
#5 5 5 5
如果有NA
个值而不是空格,我们可以使用相同的逻辑
If there are NA
values and not blanks we can use the same logic
apply(df, 1, function(x) sample(x[!is.na(x)], 1))
这篇关于R-用任何其他列中的值填充列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!