df <- data.frame(
cola = c("A","C",NA,"C"),
colb = c("A",NA,NA,"D"),
colc = c(NA,5,3,NA),
stringsAsFactors = FALSE
)
cola colb colc
1 A A NA
2 C <NA> 5
3 <NA> <NA> 3
4 C D NA
I want to print colnames first,then rownames when cell vaue is not NA,get the expect output as below:
cola=1+2+4
colb=1+4
colc=2+3
Then I tried :
df %>%
lapply(function(x){
r_name=list()
for(i in x){if(!is.na(i)) {r_name<-list(r_name,rownames(i))}}
paste0(colnames(x),'=',paste(r_name,collapse='+'))
}
)
But output is:
$cola
[1] "=list(list(list(), NULL), NULL)+NULL"
$colb
[1] "=list(list(), NULL)+NULL"
$colc
[1] "=list(list(), NULL)+NULL"
Where is the problem?