使用base R时如何包括新列? [英] How to include a new column when using base R?

查看:87
本文介绍了使用base R时如何包括新列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv文件为 Campaigname.csv

I have a csv file as 'Campaigname.csv'

AdvertiserName,CampaignName
Wells Fargo,Gary IN MetroChicago IL Metro
EMC,Los Angeles CA MetroBoston MA Metro
Apple,Cupertino CA Metro

R中所需的输出

AdvertiserName,City,State
Wells Fargo,Gary,IN
Wells Fargo,Chicago,IL
EMC,Los Angeles,CA
EMC,Boston,MA
Apple,Cupertino,CA

解决方案的代码在先前的stackoverflow答案为:

## read the csv file - modify next line as needed
xx <- read.csv("Campaignname.csv",header=TRUE)

s <- strsplit(xx$CampaignName, " Metro")
names(s) <- xx$Market
ss <- stack(s)
DF <- with(ss, data.frame(Market = ind, 
City = sub(" ..$", "", values),
State = sub(".* ", "", values)))

write.csv(DF, file = "myfile.csv", row.names = FALSE, quote = FALSE)

但现在又包括了另一列,例如'Identity',其中输入为

But now another column like 'Identity' is included where the input is

Market,CampaignName,Identity
Wells Fargo,Gary IN MetroChicago IL Metro,56
EMC,Los Angeles CA MetroBoston MA Metro,78
Apple,Cupertino CA Metro,68

期望的结果是

 Market,City,State,Identity
 Wells Fargo,Gary,IN,56
 Wells Fargo,Chicago,IL,56
 EMC,Los Angeles,CA,78
 EMC,Boston,MA,78
 Apple,Cupertino,CA,68

列数可能不仅限于3列,继续增加。

The number of columns may not be limited to just 3 columns, it may keep on increasing.

如何在R中做到这一点?

How to do it in R? New to R.Any help is appreciated.

推荐答案

我不确定我是否完全理解您的问题,而您没有请提供一个可复制的示例(因此,我无法运行您的代码并尝试达到所需的终点)。但我仍然会尽力提供帮助。

I'm not sure that I fully understand your question, and you didn't provide a reproducible example (so I can't run your code and try to get to the end point you want). But I'll still try to help.

通常来说,在R中,您可以简单地使用data.frame添加新列。

Generally speaking, in R you can add a new column to a data.frame simply by using it.

df = data.frame(advertiser = c("co1", "co2", "co3"),
                campaign   = c("camp1", "camp2", "camp3"))
df
  advertiser campaign
1        co1    camp1
2        co2    camp2
3        co3    camp3

在这一点上,如果我想添加 identity 列,则只需使用 $ 运算符像这样:

At this point, if I wanted to add an identity column I would simply create it with the $ operator like this:

df$identity = c(1, 2, 3)
df
  advertiser campaign identity
1        co1    camp1        1
2        co2    camp2        2
3        co3    camp3        3

请注意,还有其他方法可以完成此操作-请参见 transform (?transform)和 rbind (?rbind)函数。

Note that there are other ways to accomplish this - see the transform (?transform) and rbind (?rbind) functions.

向data.frame添加列时的警告是,我相信您必须添加一个向量,该向量的元素数与数据中的行数相同。帧。您可以通过键入 nrow(df)来查看data.frame中的行数。

The caveat when adding a column to a data.frame is that I believe you must add a vector that has the same number of elements as their are rows in the data.frame. You can see the number of rows in the data.frame by typing nrow(df).

这篇关于使用base R时如何包括新列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆