I am trying to calculate a survey scale score which involves subtracting from certain items. However, I am not sure how to properly add my end result back to my data frame as a proper column. Checking str(df)
I realise the computed column is nested.
# for reprex
df <- structure(list(column0 = c(10L, 10L, 10L),
column1 = c(4L, 3L, 4L),
column2 = c(2L, 3L, 4L),
column3 = c(1L, 2L, 1L),
blah = c(1L, 2L, 1L)),
class = "data.frame",
row.names = c(NA, -3L))
df
column0 column1 column2 column3 blah
1 10 4 2 1 1
2 10 3 3 2 2
3 10 4 4 1 1
# columns to subtract from
subtract.cols <- c("column1", "column2", "column3")
# sum all columns that contain "column" in the name, except subtract.cols
# store the result as column5
df$column5 <- df %>% select(contains("column")) %>%
mutate(hahaha = rowSums(.) - rowSums(.[subtract.cols]) ) %>%
select("hahaha")
Calling column5
gives me the column named hahaha
head(df %>% select("column5"))
hahaha
1 10
2 10
3 10
Apparently because hahaha
is nested within a the df column5
str(df)
'data.frame': 3 obs. of 6 variables:
$ column0: int 10 10 10
$ column1: int 4 3 4
$ column2: int 2 3 4
$ column3: int 1 2 1
$ blah : int 1 2 1
$ column5:'data.frame': 3 obs. of 1 variable:
..$ hahaha: num 10 10 10
How can I get the computed results in a normal column like the rest of my data?