How to write data to a csv file from different functions in R one by one?

I have a CSV file where I want to write data to another CSV file based on the functions that I perform, for example

data.csv

Identity,State,City,BusinessName,BusinessNeed
12,California,Los Angeles,Ray brothers,IT
34,texas,Dallas,abc,TV
45,washington,seattle,Microsft,Software

My expected output is similar to

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

How do I format the output the way I want?

My code looks like

newlistings <- read.csv("Data.csv",header=TRUE)
Identity <- newlistings$Identity
campaignname <- paste("geo","|",(tolower(as.character(newlistings$state))),"|",(tolower(as.character(newlistings$Market))),sep="")

... again, this should be the name of the campaign

campaignname <- paste("cat","|",(tolower(as.character(newlistings$BusinessName))),"|",(tolower(as.character(newlistings$BusinessNeed))),sep="")

I want to achieve this without using a loop. new to R. any help is appreciated.

+3
source share
2 answers

I thought that creating a new data frame for this was a bit wrong, so I combined the solution based on cat: (it could be easily modified to write to a file.)

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 
+1
source

Like this? (importing your Data.csv as 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
source

All Articles