我有一个CSV文件,我想根据我执行的功能将数据写入另一个CSV文件
Data.csv
Identity,State,City,BusinessName,BusinessNeed
12,California,Los Angeles,Ray brothers,IT
34,texas,Dallas,abc,TV
45,washington,seattle,Microsft,Software
我的desrired输出就像
BusinessId,Campaignname
12,geo|California|Los Angeles
12,cat|Ray brothers,IT
34,geo|texas|Dallas
34,cat|abc|TV
45,geo|washington|seattle
45,cat|Microsoft|Software
我应该如何按照自己的方式格式化输出?
我的代码看起来像
newlistings <- read.csv("Data.csv",header=TRUE)
Identity <- newlistings$Identity
campaignname <- paste("geo","|",(tolower(as.character(newlistings$state))),"|",(tolower(as.character(newlistings$Market))),sep="")
... 再次它应该是campaignname
campaignname <- paste("cat","|",(tolower(as.character(newlistings$BusinessName))),"|",(tolower(as.character(newlistings$BusinessNeed))),sep="")
我想在不使用for循环的情况下实现它。 R的新人。感谢任何帮助。
答案 0 :(得分:1)
喜欢这个? (将您的Data.csv导入为df
)
df.1 <- cbind(BusinessId=df$Identity,
Campaignname=paste("geo",tolower(df$State),tolower(df$City),sep="|"))
df.2 <- cbind(BusinessId=df$Identity,
Campaignname=paste("cat",tolower(df$BusinessName),tolower(df$BusinessNeed),sep="|"))
result <- data.frame(rbind(df.1,df.2))
result <- result[order(result$BusinessId,-result$Campaignname),]
result
# BusinessId Campaignname
# 1 12 geo|california|los angeles
# 4 12 cat|ray brothers|it
# 2 34 geo|texas|dallas
# 5 34 cat|abc|tv
# 3 45 geo|washington|seattle
# 6 45 cat|microsft|software
答案 1 :(得分:1)
我认为为此创建一个新的数据帧有点误导,所以我拼凑了一个基于cat
的解决方案:(可以很容易地修改它以写入文件。)
cat( cat('BusinessId,Campaignname','\n'),
apply( Data.csv, 1, function( ln){
cat( ln[1], ',', paste('geo', ln[2],ln[3], sep="|"), "\n")
cat( ln[1], ',', paste("cat", ln[4],ln[5], sep="|"), "\n") }))
BusinessId,Campaignname
12 , geo|California|Los Angeles
12 , cat|Ray brothers|IT
34 , geo|texas|Dallas
34 , cat|abc|TV
45 , geo|washington|seattle
45 , cat|Microsft|Software