繁体   English   中英

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

[英]multiple values in R and store it in a list

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

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

码:

     ##############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)在if语句中使用相同而不是== ?"=="此帖子

(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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM