gpt4 book ai didi

r - 使用 for 循环更改数据框中的列

转载 作者:行者123 更新时间:2023-12-04 11:48:12 27 4
gpt4 key购买 nike

我是 R 的初学者,我写了一段代码,我相信可以用 for 循环来缩短它。问题是我不知道如何编写循环。

我有一个包含“TestGrade”列的数据框,其值类似于“Grade 1”或“Kindergarten”。我正在尝试将该列更改为仅数字值。例如,'Kindergarten' 将更改为 0,'Grade 1' 将更改为 1。我将在下面提供示例数据帧的代码以及我如何在没有循环的情况下解决问题。

任何指导将不胜感激!

##Sample Data
FirstInitial <- c("A", "D", "M", "C", "J", "S", "K", "L", "M", "K", "G", "B", "F")
LastInitial <- c("S", "M", "T", "M", "A", "B", "H", "M", "S", "W", "L", "Z", "P")
TestGrade <- c('Kindergarten', 'Grade 1','Grade 2', 'Grade 3','Grade 4', 'Grade 5', 'Grade 6','Grade 7','Grade 8', 'Grade 9', 'Grade 10', 'Grade 11','Grade 12')

df <- data.frame(FirstInitial, LastInitial, TestGrade)

##The codes current function
if(any(df$TestGrade == 'Kindergarten')){
df$TestGrade <- gsub('Kindergarten', '0', df$TestGrade)
}
if(any(df$TestGrade == 'Grade 1')){
df$TestGrade <- gsub('Grade 1', '1', df$TestGrade)
}
if(any(df$TestGrade == 'Grade 2')){
df$TestGrade <- gsub('Grade 2', '2', df$TestGrade)
}
if(any(df$TestGrade == 'Grade 3')){
df$TestGrade <- gsub('Grade 3', '3', df$TestGrade)
}
if(any(df$TestGrade == 'Grade 4')){
df$TestGrade <- gsub('Grade 4', '4', df$TestGrade)
}
if(any(df$TestGrade == 'Grade 5')){
df$TestGrade <- gsub('Grade 5', '5', df$TestGrade)
}

if(any(df$TestGrade == 'Grade 6')){
df$TestGrade <- gsub('Grade 6', '6', df$TestGrade)
}
if(any(df$TestGrade == 'Grade 7')){
df$TestGrade <- gsub('Grade 7', '7', df$TestGrade)
}
if(any(df$TestGrade == 'Grade 8')){
df$TestGrade <- gsub('Grade 8', '8', df$TestGrade)
}
if(any(df$TestGrade == 'Grade 9')){
df$TestGrade <- gsub('Grade 9', '9', df$TestGrade)
}
if(any(df$TestGrade == 'Grade 10')){
df$TestGrade <- gsub('Grade 10', '10', df$TestGrade)
}
if(any(df$TestGrade == 'Grade 11')){
df$TestGrade <- gsub('Grade 11', '11', df$TestGrade)
}
if(any(df$TestGrade == 'Grade 12')){
df$TestGrade <- gsub('Grade 12', '12', df$TestGrade)
}

最佳答案

我们可以使用 ifelse , 为“幼儿园”分配 0 并从其他人中删除“等级”

as.numeric(ifelse(df$TestGrade == "Kindergarten", 0, 
sub("Grade ", "", df$TestGrade)))

#[1] 0 1 2 3 4 5 6 7 8 9 10 11 12

关于r - 使用 for 循环更改数据框中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55420509/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com