Reputation: 175
I am hoping to operate on each value in the table below to make all values equal to zero or one. If a value in the table is equal to 1,2,3, or 4 I am hoping for it to be converted to equal 1. If the value is greater than 4 (therefore between 5 and 17), then I want to be converted to zero. I'm thinking that some if else statements are needed, but am unsure how to put this together. Thank you!
structure(list(`1` = structure(c(1L, 5L, 15L, 12L, 11L, 12L,
1L, 1L), .Label = c("1", "2", "3", "4", "5", "6", "7", "8", "9",
"10", "11", "12", "13", "14", "15", "16", "17"), class = "factor"),
`2` = structure(c(12L, 10L, 17L, 11L, 1L, 5L, 1L, 1L), .Label = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
"13", "14", "15", "16", "17"), class = "factor"), `3` = structure(c(10L,
12L, 1L, 10L, 6L, 1L, 14L, 1L), .Label = c("1", "2", "3",
"4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15", "16", "17"), class = "factor"), `4` = structure(c(1L,
10L, 1L, 1L, 1L, 10L, 6L, 1L), .Label = c("1", "2", "3",
"4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15", "16", "17"), class = "factor"), `5` = structure(c(1L,
1L, 1L, 10L, 11L, 1L, 1L, 1L), .Label = c("1", "2", "3",
"4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15", "16", "17"), class = "factor"), `6` = structure(c(1L,
1L, 1L, 10L, 1L, 10L, 1L, 12L), .Label = c("1", "2", "3",
"4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15", "16", "17"), class = "factor"), `7` = structure(c(1L,
1L, 14L, 10L, 10L, 1L, 1L, 1L), .Label = c("1", "2", "3",
"4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15", "16", "17"), class = "factor"), `8` = structure(c(1L,
17L, 5L, 1L, 1L, 10L, 11L, 1L), .Label = c("1", "2", "3",
"4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15", "16", "17"), class = "factor"), `9` = structure(c(1L,
10L, 1L, 1L, 12L, 1L, 1L, 10L), .Label = c("1", "2", "3",
"4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15", "16", "17"), class = "factor"), `10` = structure(c(10L,
1L, 10L, 1L, 11L, 1L, 1L, 11L), .Label = c("1", "2", "3",
"4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15", "16", "17"), class = "factor")), row.names = c("62",
"94", "109", "145", "175", "227", "240", "244"), class = "data.frame")
Upvotes: 0
Views: 42
Reputation: 389265
Convert the factor values to integer using type.convert
, compare the dataframe with <= 4
to get logical (TRUE
/FALSE
) value which can be converted to 1/0 by using +
operator.
df <- type.convert(df)
df[] <- +(df <= 4)
df
# 1 2 3 4 5 6 7 8 9 10
#62 1 0 0 1 1 1 1 1 1 0
#94 0 0 0 0 1 1 1 0 0 1
#109 0 0 1 1 1 1 0 0 1 0
#145 0 0 0 1 0 0 0 1 1 1
#175 0 1 0 1 0 1 0 1 0 0
#227 0 0 1 0 1 0 1 0 1 1
#240 1 1 0 0 1 1 1 0 1 1
#244 1 1 1 1 1 0 1 1 0 0
Anything less than equal to 4 becomes 1 and rest becomes 0.
Upvotes: 1