我的数据集中有一个名为“Count”的特定列。我想检查此列以查看数字是奇数还是偶数,然后在新列中返回“奇数”或“偶数”的文本。我该怎么做?
这是我到目前为止所拥有的...
dat_1 <- dat %>%
mutate(Amount = as.numeric(Value_Recorded)) %>%
select(1:8, 10, 15:16) %>%
na.omit() %>%
relocate(rowID) %>%
rename(Analyte = analytes_name, Method_Num = Method_Number) %>%
group_by(Year, Season, Sample_Type, Sample_ID, Analyte) %>%
mutate(Count = round(n()/2),) %>%
ungroup()
check_odd_even <- function(number) {
if (number %% 2 == 0) {
return('Even')
} else {
return('Odd')
}
}
如何使用此函数并通过在 Count 旁边添加一列来合并到我的 dat_1 中,该列将指定它是“奇数”还是“偶数”?
R 基数的一种方式:
df = data.frame(Count = c(1, 2, 3, 4, 5))
# Use the modulo operator to return the remainder of dividing by 2
df$evenodd <- df$Count %% 2
# Relabel 0 = Even, 1 = Odd
df[df$evenodd == 0,]$evenodd = "Even"
df[df$evenodd == 1,]$evenodd = "Odd"