如何在R中创建嵌套for循环以转换表中的值
我希望对下表中的每个值进行运算,使所有值都等于零或一。如果表中的值等于1、2、3或4,我希望将其转换为等于1。如果该值大于4(因此介于5和17之间),则我希望将其转换为零。我认为需要一些if-else语句,但不确定如何将其组合起来。谢谢大家!如何在R中创建嵌套for循环以转换表中的值,r,loops,dplyr,R,Loops,Dplyr,我希望对下表中的每个值进行运算,使所有值都等于零或一。如果表中的值等于1、2、3或4,我希望将其转换为等于1。如果该值大于4(因此介于5和17之间),则我希望将其转换为零。我认为需要一些if-else语句,但不确定如何将其组合起来。谢谢大家! structure(list(`1` = structure(c(1L, 5L, 15L, 12L, 11L, 12L, 1L, 1L), .Label = c("1", "2", "3", &
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")
使用
类型将因子值转换为整数。转换,将数据帧与进行比较!非常感谢你。
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