简体   繁体   中英

need to merge output of expand.grid into a cvs file in R

I have 20 different lists variable say

a= c("red" "blue"), b= c("circle", "square"), c= c("inside","outside")

I am taking the combinations between different list by the command:

 data1 <- expand.grid(a, b) 
 data2 <- expand.grid(a, d) 

I want to merge all the output of data1 , data2 into a single data set.

I would like to export the data into a cvs file.

For you example given, you could do this:

all_combined <- do.call("rbind",
  lapply(combn(list(a, b, c), 2, simplify = FALSE),
    do.call, what = "expand.grid")
)

Output

#     Var1    Var2
#1     red  circle
#2    blue  circle
#3     red  square
#4    blue  square
#5     red  inside
#6    blue  inside
#7     red outside
#8    blue outside
#9  circle  inside
#10 square  inside
#11 circle outside
#12 square outside

If you just wanted specific combinations, you could do:

data1 <- expand.grid(a, b)
data2 <- expand.grid(a, c)

combined <- rbind(data1, data2)

This could then be written to CSV using:

write.csv(combined, "CombinedData.csv")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM