如何在R中的小数据帧中向新变量添加因子?

如何在R中的小数据帧中向新变量添加因子?,r,R,快速提问:我有一个小数据集,现在我想添加一个列变量: > df taxa spring summer fall LocationA LocationB 1 Chironominae 1957.50 537.54 3396.765 1712.196 2958.642 2 Culicoides 863.53 343.08 2796.647 1907.804 1384.642 3 Naididae 949.88 40.75 147.5

快速提问:我有一个小数据集,现在我想添加一个列变量:

> df
          taxa  spring summer     fall LocationA LocationB
1 Chironominae 1957.50 537.54 3396.765  1712.196   2958.642
2   Culicoides  863.53 343.08 2796.647  1907.804   1384.642
3     Naididae  949.88  40.75  147.569   641.911     91.566
4     Asioplax 1799.41 163.04  119.882     0.000   1343.528
5     Nematoda    0.00 166.00   27.647    53.679     45.057
6  Stilobezzia    0.00  20.38  885.961   605.179    222.321

taxa <- melt(df)

> taxa
           taxa   variable    value
1  Chironominae     spring 1957.500
2    Culicoides     spring  863.530
3      Naididae     spring  949.880 .....
>df
分类群春季夏季秋季位置A位置B
1摇号1957.50537.543396.7651712.1962958.642
2库蠓863.53 343.08 2796.647 1907.804 1384.642
3 Naididae 949.88 40.75 147.569 641.911 91.566
4 Asioplax 1799.41 163.04 119.882 0.000 1343.528
5线虫0.00 166.00 27.647 53.679 45.057
6 Stilobezia 0.00 20.38 885.961 605.179 222.321
分类单元
分类变量值
1摇蚊之春1957.500
2库蚊春季863.530
3奈迪代斯普林949.880。。。。。
如何为“variable.type”添加一列,定义“variable”是季节(第1:18行)还是位置(第19:30行)?我试过:

taxa$variable.type <- c("Season"[1:18], "Location"[19:30])
taxa$variable.type尝试:


df$variable.type你太棒了!他很有魅力。很高兴知道我可以使用ifelse和一个因子。:)您确定这是您想要的数据回流方式吗?季节和位置是分类群中两个不同的数据概念,最好不要在分类群中改变位置。是的,我知道。我也一直在考虑这个问题。。。我正试图找到一种有用的方法来向非科学家总结数据,这让我离我正在玩的情节又近了一步。谢谢你的评论!
df$variable.type <- ifelse(df$variable %in% c("spring","summer","fall"),"season","location")