Reputation: 13
I would like to create a text string from a dataframe, but specify which rows will add to the text string.
Here is an example dataframe:
x <- as.data.frame(matrix(nrow = 4, ncol = 2))
x$V1 <- c(1, 1, 1, 2)
x$V2 <- c("aa", "bb", "cc", 1)
x$V3 <- c(1, 2, 3, NA
I only want to build the text strings where x$V1 = 1
.
The result I am looking for is something like "aa 1 bb 2 cc 3"
, where the row where x$V1 = 2
is ignored for the building of the text string.
I have tried the following:
x$V4 <- for(i in 1:length(x$V1)){
if (x[i, 1] == 1){
paste(x[i,2], x[i,3])
} else {""}
}
paste(x$V3, collapse = "")
The above code does not even create a V4
column in my dataframe.
Thanks for the help.
Upvotes: 1
Views: 92
Reputation: 11150
Here's a one line solution using base R -
do.call(paste, c(x[x$V1 == 1, -1], collapse = " "))
[1] "aa 1 bb 2 cc 3"
Upvotes: 1
Reputation: 15072
You can use ifelse
to do this. In general you can't assign from a for
loop in the way you are attempting to do; you should assign from inside the loop. But it is much better to avoid loops.
x <- as.data.frame(matrix(nrow = 4, ncol = 2))
x$V1 <- c(1, 1, 1, 2)
x$V2 <- c("aa", "bb", "cc", 1)
x$V3 <- c(1, 2, 3, NA)
x$V4 = ifelse(x$V1 == 1, paste(x$V2, x$V3), "")
paste(x$V4, collapse = " ")
#> [1] "aa 1 bb 2 cc 3 "
Created on 2018-10-15 by the reprex package (v0.2.0).
Upvotes: 0