I would like to use lapply
to label the values of specific variables. I have found an example that gets me close (here), but I can't get it to work for only certain variables in the data set.
Working example:
df1 <- tribble(
~var1, ~var2, ~var3, ~var4,
"1", "1", "1", "a",
"2", "2", "2", "b",
"3", "3", "3", "c"
)
Here is the code that seems like it should work, but doesn't:
df1["var1", "var2"] <- lapply(df1["var1", "var2"], factor,
levels=c(1,
2,
3),
labels = c("Agree",
"Neither Agree/Disagree",
"Disagree"))
The code runs, but give the following output:
# A tibble: 4 x 4
var1 var2 var3 var4
* <chr> <chr> <chr> <chr>
1 1 1 1 a
2 2 2 2 b
3 3 3 3 c
4 <NA> <NA> <NA> <NA>
If I try with just one variable, it works:
df1["var1"] <- lapply(df1["var1"], factor,
levels=c(1,
2,
3),
labels = c("Agree",
"Neither Agree/Disagree",
"Disagree"))
It gives the following output (which is correct):
# A tibble: 3 x 4
var1 var2 var3 var4
<fctr> <chr> <chr> <chr>
1 Agree 1 1 a
2 Neither Agree/Disagree 2 2 b
3 Disagree 3 3 c
I have tried a lot of different ways to change the code to get it to work, but I just can't figure it out.