I have a condition and I would like two things two happen in case the condition is met. When I put them in a single if..else statement the code does not give me the desired output. But when I run them separately it works. Can you please tell me what is wrong?
What I aim to do in the first part is to create a new column called id and then use this column as row names.
data1 <- lapply(data, function(y) {
lapply(y, function(z) {
if(all(c("variable", "missing") %in% names(z))) {
z %>% mutate(id = paste0(z[["variable"]], sep= "_", row_number()))
} else z
})
})
data2 <- lapply(data1, function(y) {
lapply(y, function(z) {
if(all(c("variable", "missing") %in% names(z))) {
`rownames<-`(z, z[["id"]])
} else z
})
})
This is the single statement version which doesn’t work:
data1 <- lapply(data, function(y) {
lapply(y, function(z) {
if(all(c("variable", "missing") %in% names(z))) {
z %>% mutate(id = paste0(z[["variable"]], sep= "_", row_number()));
`rownames<-`(z, z[["id"]])
} else z
})
})
>Solution :
z %>% mutate(id = paste0(z[["variable"]], sep= "_", row_number())) works as a one-liner because its result will be implicitly returned by the function. However, because you don’t assign the result with <- the change is not saved, so when you have multiple lines you need to use <-, change it to z <- z %>% mutate(id = paste0(z[["variable"]], sep= "_", row_number())) and it will work in the multi-line statement.
data1 <- lapply(data, function(y) {
lapply(y, function(z) {
if(all(c("variable", "missing") %in% names(z))) {
## simplifying paste per r2evans's comment
z <- z %>% mutate(id = paste0(z[["variable"]], "_", row_number()))
## I'd switch your row-names to a normal assignment for readability
rownames(z) <- z[["id"]]
## the last thing will be returned
z
} else z
})
})