使用扫描对数据帧的特定用户输入

时间:2017-09-05 00:30:09

标签: r

y <- as.numeric (readline(prompt="How many metabolites?: ")) # Get no. metabolites used 
x <- as.numeric (readline(prompt="How many concs?: ")) # Get no. concentrations of each metabolite used

print(paste("enter", y," metabolite names separated by return: ")) # User input for metabolite names
c <- scan(nmax=y,what = character())

到目前为止,我们已经捕获了代谢物的数量,浓度的数量和代谢物的名称。

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

此代码捕获x种不同的代谢物浓度。关于如何扩展这一点的任何想法?:

  • 捕获y代谢物的x个浓度(x的值对于不同的代谢物会有所不同,但值的数量是不变的。)

假设x = 5,y = 2(用户指定的conc值)所需的输出:

metabolite  conc1  conc2   conc3  conc4  conc5
metabolite1  100     10      1      0.1    0.001
metabolite2  10      1      0.1    0.01     0.001

1 个答案:

答案 0 :(得分:0)

这是你希望做的事情

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

print(paste("enter", y, " metabolite names separated by return: "))
c <- scan(nmax = y, what = character())

data <- matrix(nrow = x, ncol = y)

for (metab in 1:y) {
    print(paste("enter", x, " numbers for metabolite", c[metab], "separated by return: "))
    data[metab, ] <- scan(nmax = x, what = double())
}

df <- as.data.frame(data)
df <- cbind(c, df)
colnames(df) <- c("metabolite", paste0("conc", 1:x))
df

但是我根本不建议这样做,而是你应该自己生成一个csv,所以你有

<强> conc_data.csv

metabolite,conc1,conc2,conc3,conc4,conc5
metabolite1,100,10,1,0.1,0.001
metabolite2,10,1,0.1,0.01,0.001

并在您的代码中

df <- read.csv("conc_data.csv")

您可以在excel中填写csv,然后使用save as然后在文件类型中选择CSV。始终使用文本编辑器打开该csv文件以检查excel是否未插入额外的列或行。