简体   繁体   English

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

[英]How do I add factors to a new variable in a small dataframe in R?

Quick question: I have a small dataset that I melted and now would like to add a column variable: 快速的问题:我有一个小的数据集,我现在融化了,现在想添加一个列变量:

> 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 .....

How do I add a column for "variable.type" that defines whether the "variable" is a season (rows 1:18) or a location (rows 19:30)? 如何为“ variable.type”添加一列,以定义“变量”是季节 (行1:18)还是位置 (行19:30)? I tried: 我试过了:

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

but just ended up with a column with lots of NAs. 但是刚结束时有很多NA的专栏。

thanks! 谢谢!

尝试:

df$variable.type <- ifelse(df$variable %in% c("spring","summer","fall"),"season","location")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将条件指示器变量添加到 R 中的数据帧? - How do I add a conditional indicator variable to a dataframe in R? 我如何使用 R 中的 tidyeval 创建一个包含所有级别因子的小型预测数据集? - How do I use tidyeval in R to create a small prediction dataset that has all levels of factors? 如何计算因子频率并在R中的新数据框中进行组织 - How to count factors frequency and organize in a new dataframe in R 如何使用新名称在 R 中重复向 dataframe 添加新列? - How do I add new columns to a dataframe repeatedly in R with new names? R-如何将新列添加到数据框中,这是另一列的计算结果 - R - How do I add a new column to a dataframe that is the calculated result of another column 如何在不使用长变量值作为新变量名的情况下将 R dataframe 从长改型为宽? - How do I reshape an R dataframe from long to wide without using the long variable values as the new variable names? 如何添加新列,并基于R中的另一个列变量填写变量? - How do I add a new column, and fill in the variables based on another columns variable in R? 将数据帧与数据帧列表匹配,并将新变量添加到R中的列表中 - match a dataframe to a list of dataframe and add a new variable to the list in R 如何自动向数据框添加新列? (R) - How do I automate adding new columns to dataframe? (R) 我如何通过&#39;&lt;&#39;对R中的因子错误没有意义? - How do I get pass the '<' not meaningful for factors error in R?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM