问题
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.
Let's assume this is my dataframe 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
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")
Edit Included 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 " " " " " " " " ...
回答1:
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
Original Answer
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
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))
回答2:
you can simply type as following:df$Col5 <- 1:5df$Col5 will create a Col5 in df and 1:5 just add the series number there.
回答3:
Try this:
df <- data.frame(col1 = c(1, NA, 3), col2 = c(1, 2, NA), col3 = c(NA, 2, 3),col4 = rep(NA, 3))
for (i in 1:nrow(df)) {
df[i, 4] <- df[i, which(!is.na(df[i,]))][, 1]
}
df
That will produce:
> df <- data.frame(col1 = c(1, NA, 3), col2 = c(1, 2, NA), col3 = c(NA, 2, 3), col4 = rep(NA, 3))
> df
col1 col2 col3 col4
1 1 1 NA NA
2 NA 2 2 NA
3 3 NA 3 NA
> for (i in 1:nrow(df)) {
+ df[i, 4] <- df[i, which(!is.na(df[i,]))][, 1]
+ }
+ df
+
col1 col2 col3 col4
1 1 1 NA 1
2 NA 2 2 2
3 3 NA 3 3
回答4:
Here is a vectorized option with max.col
df$Treat_Four <- df[1:3][cbind(1:nrow(df), max.col(sapply(df[1:3], trimws)!='', "first"))]
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
来源:https://stackoverflow.com/questions/42185450/r-fill-column-with-values-from-any-other-columns