Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

paste with condition in R

Tags:

r

paste

I like to create a vector with function paste0 with condition if the value is greater than 0, paste the value in each rownames.

ts <- data.frame(t2)
ts

1  1
2  1
3  0
4  0
5  0
6  2
footer <- c(paste0("There is ",ts$t2[1]," subject missing in group  ",rownames(ts)[1]),
paste0("There is ",ts$t2[2]," subject missing in group ",rownames(ts)[2]),
paste0("There are ",ts$t2[6]," subjects missing in group ",rownames(ts)[6]))
footer
[1] "There is 1 subject missing in group 1"   "There is 1 subject missing in group 2"  
[3] "There are 2 subjects missing in group 6"

Thanks for your advance.

like image 436
BIN Avatar asked Dec 03 '25 17:12

BIN


1 Answers

How about a nice little sapply with a switch thrown in for good measure

ts <- data.frame(t2 = c(1,1,0,0,0,2))

s <- which(rowSums(ts) > 0)

sapply(s, function(x) paste0("There ", switch(ts[x, ], "1" = "is ", "are "), ts[x,], " missing from group ", x))

# [1] "There is 1 missing from group 1"  "There is 1 missing from group 2"  "There are 2 missing from group 6"
like image 104
SymbolixAU Avatar answered Dec 06 '25 07:12

SymbolixAU



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!