【发布时间】:2014-06-19 06:43:38
【问题描述】:
我想根据列的值范围对数据进行排序。我的数据很大,但我做了一个小数据集作为工作示例:
cats colour length weight mew
1 5 3 3 0
2 4 4 2 0
3 3 5 3 0
4 2 9 4 1
5 4 22 1 1
43 43 90 0
22
15 32 45
25
32 23 4 0
35 2 29
这是我的 broken 代码,它应该基于列排序并根据列的值添加一个虚拟列:
x <- data$cats # how to refer to a column: name_of_data_set_$_what column you want e.g. data$mass
x$dog <- ifelse(x$x>0 & x$x>3)
animal <- function(x) {
if ( x > 0 | x <3) {
return(cbind( data , dog = 0))
} else { if (x > 4 | x < 6) {
return(cbind( data , dog = 1))
} else {
return(cbind( data , dog = 2))
}
}
}
animal(x)
summary(animal)
dput(head(data, 10))
animal(x)
代码应该做什么:
所以列是 1、2、3 和 4 应该是这样的:
cats colour length weight mew dog
1 5 3 3 0 0
2 4 4 2 0 0
3 3 5 3 0 0
4 2 9 4 1 1
5 4 22 1 1
43 43 90 0
22
15 32 45
25
32 23 4 0
35 2 29
【问题讨论】:
-
用
data <- read.csv(..., stringsAsFactors = FALSE)重新阅读并重试。此外,您的函数中不会发生排序。 -
请用
dput(head(data, 10))的输出发布可重现的数据,我会进一步解释。 -
我将该代码添加到底部:结构(列表(cats.colour.length.weight.mew =结构(c(3L,5L,7L,8L,9L,1L,2L,6L, 4L), .Label = c(",43,,,", "0,23,1,,1", "1,5,3,3,0", "13,1,,2,", " 2,4,4,20,1", "23,11,,,", "3,3,5,30,0", "4,2,9,43,0", "5,1,4 ,22,1"), class= "因子")), .Names = "cats.colour.length.weight.mew", row.names = c(NA, 9L), class= "data.frame")
-
抱歉,我的意思是要发布来自
dput(data)的结果。也请从animal(x)发布结果
标签: r if-statement dataset multiple-columns large-data