我在R中有一个数据帧,并且我正在尝试添加一个使用info的新列。从其他列中的一列。
具体地说,我有一个有机体的年龄(在一个专栏中),我试图在新的专栏中像这样对它们进行分组。
1-3岁:婴儿
4-6岁:幼儿等。
这是在R演播室。
我尝试过使用一些if else语句,但它们就是不起作用。
发布于 2019-10-27 12:07:34
使用ifelse a base-r解决方案
df$Category <- ifelse(df$Age<=3, "Infant", ifelse(df$Age<=6, "Toddler", ifelse(df$Age<=13, "Adolescence", ifelse(df$Age<=19, "Teenage", ifelse(df$Age<=59, "Adult", "Senior")))))
# -------------------------------------------------------------------------
# df
# Id Age Category
# 1 1 1 Infant
# 2 2 5 Toddler
# 3 3 10 Adolescence
# 4 4 12 Adolescence
# 5 5 3 Infant
# 6 6 23 Adult
# 7 7 55 Adult
# 8 8 42 Adult
# 9 9 92 Senior
# 10 10 78 Senior
# 11 11 33 Adult
# 12 12 44 Adult
# 13 13 25 Adult
# 14 14 13 Adolescence
# 15 15 10 Adolescence
# 16 16 19 Teenage
# 17 17 45 Adult
# 18 18 39 Adult使用dplyr mutate和case_when
library(dplyr)
df <- df %>%
mutate(Category =
case_when(
Age <=3 ~ "Infant",
Age <=6 ~ "Toddler",
Age <=13 ~ "Adolesence",
Age <=19 ~ "Teenage",
Age <=59 ~ "Adult",
TRUE ~ "Senior"
)
)
# -------------------------------------------------------------------------
# df
# Id Age Category
# 1 1 1 Infant
# 2 2 5 Toddler
# 3 3 10 Adolesence
# 4 4 12 Adolesence
# 5 5 3 Infant
# 6 6 23 Adult
# 7 7 55 Adult
# 8 8 42 Adult
# 9 9 92 Senior
# 10 10 78 Senior
# 11 11 33 Adult
# 12 12 44 Adult
# 13 13 25 Adult
# 14 14 13 Adolesence
# 15 15 10 Adolesence
# 16 16 19 Teenage
# 17 17 45 Adult
# 18 18 39 Adult
# 查看上面的注释,以及您需要提供一个可重复的示例,以获得针对您特定问题的解决方案目标。提供一个可重现的示例可以保证快速响应。
样本数据
df <- data.frame(Id = seq(1,18,1),
Age = c(1,5,10, 12, 3, 23, 55, 42, 92, 78, 33, 44, 25, 13, 10, 19, 45, 39))希望这能有所帮助。
发布于 2019-10-27 12:15:47
下面是一个具有专用函数来确定类别的工作示例:
#define sample
organism <- c('cat','dog','horse','elephant','snake','ant','bear')
ages <- c(1,4,7,2,5,2,1)
df <- data.frame(organism,ages)
#define classification function
classify_age <- function(age) {
if (age >= 1 & age <= 3)
{return ("infant")}
else if (age >= 4 & age <= 6)
{return ("toddler")}
else
{return("adult")}
}
#create the new data frame column
df$category <- lapply(df$ages, classify_age)
#print data frame
dfhttps://stackoverflow.com/questions/58576322
复制相似问题