R中的多个值并将其存储在列表中

时间:2014-11-17 02:48:34

标签: r console user-input

我想从控制台获取用户输入。 薪水,公司名单和工作清单。

我能够将公司和工作的个人价值作为控制台中的角色,但如何获取多个值并将其存储在变量中以供进一步分析?我需要存储和访问这些值。

代码:

     ##############Classs Declaration############
     setClass(Class="User",
             representation(
               salary="numeric",
               company="character",
               jobtitle="character"

             ))
    ###############Function Declaration##########
    myFunction <- function(){ 
      sal <- readline("Salary?")  
      comp <- readline("Company?")
      job <- readline("Job Title?")

      sal <- as.numeric(unlist(strsplit(sal, ",")))
      comp <- as.character(comp)
      job <- as.character(job)

      return(new("User",
                 salary=sal,
                 company=comp,
                 jobtitle=job

                 ))
    }

    ##########Calling the function########
    aUser = if(interactive()) myFunction()

提前谢谢

1 个答案:

答案 0 :(得分:2)

这是你想要的吗?

一些注意事项:

(1)在if语句中使用相同而不是==?"=="this post

(2)我不认为你可以从命令行轻松地以交互方式运行它。如果有人知道如何将此R脚本作为shell命令发布为评论。

(3)您可以使用dputwrite命令将结果存储到静态文件中以供日后使用。

# result variable is an array used to store user input
# remove result variable from the environment
if(exists("result")){remove(result)}
while(identical(flag_continue <- readline("continue?:"), "y")){
    aUser <- myFunction()
    if(!exists("result")){
      result <- c(aUser)
    } else {
      result <- c(aUser, result)
    }    
}
# now all the user typed info has been stored inside a list called "result"

输出:

continue?:y
Salary?1
Company?com1
Job Title?job1
continue?:y
Salary?2
Company?com2
Job Title?job2
continue?:n
> str(result)
List of 2
$ :Formal class 'User' [package ".GlobalEnv"] with 3 slots
.. ..@ salary  : num 2
.. ..@ company : chr "com2"
.. ..@ jobtitle: chr "job2"
$ :Formal class 'User' [package ".GlobalEnv"] with 3 slots
.. ..@ salary  : num 1
.. ..@ company : chr "com1"
.. ..@ jobtitle: chr "job1"

此外,您可以将嵌套列表类... etc ... result对象转换为数据框:

convertUser <- function(result){ 
  data.frame(
    salary = unlist(lapply(result, FUN=function(x){attr(x, "salary")})),
    company = unlist(lapply(result, FUN=function(x){attr(x, "company")})),
    jobtitle = unlist(lapply(result, FUN=function(x){attr(x, "jobtitle")}))
  )
}
df <- convertUser(result)

现在df看起来像这样:

> convertUser(result)
salary company jobtitle
1      3    com2     job3
2      2    com2     job2
3      1    com1     job1