For example: Here we have the table:
Height---H_Or_L
20-------High
30-------High
5--------Low
6--------Low
We need the exact format when converted into a data frame for vectors:-
Height = c(20, 30, 5, 6)
H_or_L = c("High", "Low")
Is it possible to convert these two vectors into a data frame to produce the exact table above?
If done, data.frame(Height, H_or_L), the table it produce will be:
Height---H_Or_L
20-------High
30-------Low
5--------High
6--------Low
Is there any standard method to do this? (not using loops)
Or making H_or_L = c("High", "High", "Low", "Low") only choice, if loops are not used?
CodePudding user response:
As you found out, default vector repeating is to repeat the entire vector, not to repeat individual items.
To repeat individual items, we can make a oneliner for any required length (I have made Height
to be 5 items long this time:
Height = c(20, 30, 5, 6, 7)
H_or_L = c("High", "Low")
rep(H_or_L, each = ceiling(length(Height)/length(H_or_L)))[1:length(Height)]
Result:
> rep(H_or_L, each = ceiling(length(Height)/length(H_or_L)))[1:length(Height)]
[1] "High" "High" "High" "Low" "Low"