SmallTodge
SmallTodge

Reputation: 23

R: Specific user input to dataframe

Any suggestions on a much cleaner version of the following? The output should be a data.frame of two columns as seen below. The user inputs response to 'how many concs?' and should create matrix with this this number (saved as y). Then the value for each conc must be inputted (saved as a)

x <- as.numeric (readline(prompt="How many concs?: ")) 

if(x == 6) {
  y <- c("conc 1","conc 2","conc 3","conc 4","conc 5", "conc 6")
  a <- as.integer(strsplit(readline(prompt="enter 6 numbers separated by 
space: "), " ")[[1]])
  cbind(y,a)
}
if(x == 5) {
  y <- c("conc 1","conc 2","conc 3","conc 4","conc 5")
  a <- as.integer(strsplit(readline(prompt="enter 5 numbers separated by 
space: "), " ")[[1]])
  cbind(y,a)
}
if(x == 4) {
  y <- c("conc 1","conc 2","conc 3","conc 4")
  a <- as.integer(strsplit(readline(prompt="enter 4 numbers separated by 
  space: "), " ")[[1]])
  cbind(y,a)
}
if(x == 3) {
  y <- c("conc 1","conc 2","conc 3")
  a <- as.integer(strsplit(readline(prompt="enter 3 numbers separated by 
  space: "), " ")[[1]])
  cbind(y,a)
}
if(x == 2) {
  y <- c("conc 1","conc 2")
  a <- as.integer(strsplit(readline(prompt="enter 2 numbers separated by 
space: "), " ")[[1]])
  cbind(y,a)
}
if(x == 1) {
  y <- c("conc 1","conc 2")
  a <- as.integer(strsplit(readline(prompt="enter 1 number: "), " ")
[[1]])
  cbind(y,a)
}

Upvotes: 0

Views: 339

Answers (1)

xraynaud
xraynaud

Reputation: 2146

You don't need all those ifs and I'll suggest you use scan instead of readline.

x <- as.numeric (readline(prompt="How many concs?: ")) 
y <- paste("conc",1:x)

print(paste("enter", x," numbers separated return: "))
a <- scan(nmax=x,what=double())
df =  data.frame(conc=y,value=a)

Upvotes: 1

Related Questions