Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

create multiple columns with each column as a sequence of numbers in R

$
0
0

Problem: I wanted to add three columns in my data frame with each column being a sequence of numbers. But I want each column to vary with the other column. So here's an example data frame:

data <- read.table(text="
group1  group2  rate
A     D     0.01     
A     D     0.001
A     D     0.0001  
B     D     0.01    
B     D     0.001      
B     D     0.0001
D     A     0.01     
D     A     0.001
D     A     0.0001  
D     B     0.01    
D     B     0.001      
D     B     0.0001",
                   header=TRUE)

So first I extended my data frame to accommodate the combinations of numbers that I want for the 3 columns. I used 125 because I have 5 numbers for each sequence.

dataext <- data[rep(seq_len(nrow(data)), 125), ]

Then, I created my new column using the sequence of number that I want:

dataext$var1 <- rep_len (seq(0,1, 0.25), length.out=125)
dataext$var2 <- rep_len (seq(0,1, 0.25), length.out=125)
dataext$var3 <- rep_len (seq(0,1, 0.25), length.out=125)

An example of my desired output is:

group1  group2  rate    var1    var 2   var3
    A     D     0.01     0      0       0           
    A     D     0.001    0      0       0               
    A     D     0.0001   0      0       0
    A     D     0.01     0.25   0       0           
    A     D     0.001    0.25   0       0               
    A     D     0.0001   0.25   0       0
    A     D     0.01     0.25   0.25    0           
    A     D     0.001    0.25   0.25    0               
    A     D     0.0001   0.25   0.25    0
    A     D     0.01     0.25   0.25    0.25            
    A     D     0.001    0.25   0.25    0.25                
    A     D     0.0001   0.25   0.25    0.25

I hope this is clear enough. Any leads on how to do it right are greatly appreciated. Thanks!


Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>