你好我是R的新手,我需要一些帮助
我有这样的数据
ID Age Sex
A01 30 m
A02 35 f
B03 45 m
C99 50 m
...
我想创建一个像这样的条件的新列组
if data1$age <30 then Group is = 1
else if data1$age >=30 and data1$age <40 then Group = 2
else if data1$age >=40 and data1$age <50 then Group = 3
else data1$age >=50 group = 4
ID Age Sex Group
A01 30 m 2
A02 35 f 2
B03 45 m 3
C99 50 m 4
我如何在R
中做到这一点答案 0 :(得分:4)
您可以尝试findInterval
,可以像这样使用(使用@Tim的示例数据):
> findInterval(data1$Age, c(0, 30, 40, 50))
[1] 2 2 3 4
答案 1 :(得分:2)
一些优秀的老式Base R将为您的问题派上用场:
data1 <- data.frame(ID=c("A01", "A02", "B03", "C99"),
Age=c(30, 35, 45, 50),
Sex=c("m", "f", "m", "m"))
data1$Group[data1$Age < 30] <- 1
data1$Group[data1$Age >= 30 & data1$Age < 40] <- 2
data1$Group[data1$Age >= 40 & data1$Age < 50] <- 3
data1$Group[data1$Age >= 50] <- 4
> data1
ID Age Sex Group
1 A01 30 m 2
2 A02 35 f 2
3 B03 45 m 2
4 C99 50 m 4
顺便说一句,您在示例中错误地分类了ID A01
。由于他的年龄是30岁,他根据你的逻辑属于第2组。
答案 2 :(得分:2)
我们也可以使用- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: [NSString stringWithFormat:@"Cell%d", indexPath.row] forIndexPath:indexPath];
if ([self isAvailableRow: indexPath.row]){
cell.backgroundColor = [UIColor whiteGreen];
}else{
cell.backgroundColor = [UIColor colorWithGreen:0.95 alpha:1];
}
int intForStrin =[[self.indexArray objectAtIndex:0] intValue];
int index = [[self.indexArray objectAtIndex:1] intValue]
if (indexPath.row == 0 && index == 0 && intForStrin == 1) {
cell.imageView.image = [UIImage imageNamed:@"5.png"];
}
else if (indexPath.row == 0 && index == 0 && intForStrin == 3) {
cell.imageView.image = [UIImage imageNamed:@"2.png"];
}
else if (indexPath.row == 1 && index == 1 && intForStrin == 1) {
cell.imageView.image = [UIImage imageNamed:@"5.png"];
}
else if (indexPath.row == 1 && index == 1 && intForStrin == 3) {
cell.imageView.image = [UIImage imageNamed:@"2.png"];
}
return cell;
}
cut
编辑:基于@ thelatemail的评论。