根据用户选择的索引在r中的数据框中设置列的子集

时间:2019-03-19 06:33:10

标签: r dataframe subset

我必须向用户提供数据框中所有可用列的列表,并且用户应输入需要作为子集的列的所有索引。现在我想使用索引的用户输入来设置数据框

示例步骤 (1)显示并要求用户从数据框(df)中选择列名称 (2)用户选择:1、2、3、4、5 (3)创建一个仅包含来自大型数据框df

的第1,2,3,4,5列的数据框

2 个答案:

答案 0 :(得分:0)

由于您没有提供任何示例数据来使用,因此社区很难为您提供帮助。请阅读how to post your question

根据您对问题的理解,我已编写了一个代码段,但这未经验证。做必要的修改。

library(stringr)
cols <- colnames(inputdf)
cat(paste("Available column names are :", cols))
cat("Enter your choices seperated by ',':")
choices <- readline()
choices <- str_split(choices, pattern = ",")
choices <- as.numeric(unlist(choices))
outputdf <- subset.data.frame(inpudf, select = choices)

答案 1 :(得分:0)

我能够使用以下代码解决我的问题。

子集必需的元素

test_function<-function(data)
{ 
  prompt<-paste(which(colnames(data)==names(data)),'-',names(data))
  print(do.call(cat, c('Input column index numbers',as.list(prompt), sep="\n")))
  return(data[,c(as.numeric(unlist(strsplit(readline('Enter the column index number'),split=',')) ))])
}

subset_for_tuning <- test_function(Datadf)