[英]How do I create a new column based on the values of an existing column in R?
I have a column for treatment names, unfortunately, the treatment is currently coded so that 1 = 0 kg N/ha, 2 = 40 kg N/ha, 3 = 80 kg N/ha, and so on.我有一列处理名称,不幸的是,处理当前编码为 1 = 0 kg N/ha,2 = 40 kg N/ha,3 = 80 kg N/ha,依此类推。 I'd like to add a column for the nitrogen rate applied to each treatment.
我想为应用于每个处理的氮率添加一列。
Here's what I've tried:这是我尝试过的:
dput(head(df))
structure(list(Treatment = c("1", "10", "11", "12", "2", "3"),
slope = c(-355.55, -136.125, -137.6625, -96.5, -284.2375,
-334.5375)), row.names = 11:16, class = "data.frame")
df$Nrate[which(df$Treatment == 1)] = 0
I get the following error, which I don't understand because there's no reason that I can see why the new column should be any shorter than the old column:我收到以下错误,我不明白,因为我没有理由明白为什么新列应该比旧列短:
Error in `$<-.data.frame`(`*tmp*`, Nrate, value = c(0, NA, NA, NA, NA, :
replacement has 49 rows, data has 60
Also, I'm not sure how to create a whole column based on all the existing values, where treatment 1 & 7 = 0, treatment 2 & 8 = 40, treatment 3 & 9= 80, treatment 4 & 10 = 120, treatment 5 & 11 = 160, and treatment 6 & 12 = 200. With this code, it looks like it creates a new column with NAs where any number other than 1 is, and I suspect that if I wrote a new line to replace 2 with 40, it would not retain the information that 1 = 0. Any insight into the correct package to use or any sample code that can create a new column based on an existing one would be much appreciated.另外,我不确定如何根据所有现有值创建一整列,其中处理 1 & 7 = 0,处理 2 & 8 = 40,处理 3 & 9 = 80,处理 4 & 10 = 120,处理5 & 11 = 160,处理 6 & 12 = 200。使用此代码,看起来它创建了一个包含 NA 的新列,其中包含 1 以外的任何数字,我怀疑如果我写了一个新行来替换 2 40,它不会保留 1 = 0 的信息。对要使用的正确包的任何见解或可以基于现有列创建新列的任何示例代码都将不胜感激。
You may try this approach.你可以试试这个方法。
df$Nrate <- factor(df$Treatment)
levels(df$Nrate)=list("0"=c(1, 7), "40"=c(2, 8), "80"=c(3, 9),
"120"=c(4, 10), "160"=c(5, 11), "200"=c(6, 12))
df
# Treatment slope Nrate
# 11 1 -355.5500 0
# 12 10 -136.1250 120
# 13 11 -137.6625 160
# 14 12 -96.5000 200
# 15 2 -284.2375 40
# 16 3 -334.5375 80
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.