R中的不同功能输出和打印选项

时间:2018-12-12 18:50:33

标签: r

我有一个数据框xsubject函数。

数据

dput(head(x))
structure(list(subjects = c(14L, 14L, 14L, 14L, 14L, 14L), 
visit =  structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("0", "1", "2"), class = "factor"),
room = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("bedroom", 
"den", "dining room", "family  room", "hall", "kitchen", 
"living room", "office", "study room", "tv room"), class = "factor"), 
value = c(6, 6, 2.75, 2.75, 2.75, 2.75), timepoint = 53:58),
row.names = c(NA, 6L), class = c("LongitudinalData", "data.frame"))

功能

subject<-function(x,id) UseMethod("subject")
subject.LongitudinalData<- function(x ,id) { 
    a<- x[x$subjects==id,]
    b<-noquote(paste("Subject ID:",id))
    out<-list(a,b)
    class(out)<-"subject"
    invisible(out)
}

现在我想获得以下打印结果(可支配的支出,不是实际的):

out<-subject(x,14)
print(out)
Subject ID: 14
理想的str输出如下所示(数据框而不是列表
str(out)
Classes ‘LongitudinalData’ and 'data.frame':    10 obs. of  5 variables:
$ subjects : int  14 14 14 14 14 14 14 14 14 14 ...
$ visit    : Factor w/ 3 levels "0","1","2": 1 1 1 1 1 1 1 1 1 1 ...
$ room     : Factor w/ 10 levels "bedroom","den",..: 1 1 1 1 1 1 1 1 1 1 ...
$ value    : num  6 6 2.75 2.75 2.75 2.75 6 6 2.75 2.75 ...
$ timepoint: int  53 54 55 56 57 58 59 60 61 62 ...

无法解决建议的解决方案及其输出

print.subject  <- function(x) {  
x[[2]]
  }
str(out)
List of 2
 $ :Classes ‘LongitudinalData’ and 'data.frame':    6 obs. of  5 variables:
  ..$ subjects : int [1:6] 14 14 14 14 14 14
  ..$ visit    : Factor w/ 3 levels "0","1","2": 1 1 1 1 1 1
  ..$ room     : Factor w/ 10 levels "bedroom","den",..: 1 1 1 1 1 1
  ..$ value    : num [1:6] 6 6 2.75 2.75 2.75 2.75
  ..$ timepoint: int [1:6] 53 54 55 56 57 58
 $ : 'noquote' chr "Subject ID: 14"
 - attr(*, "class")= chr "subject"

我不想要两个元素的列表,而是一个数据框

有什么主意吗?

2 个答案:

答案 0 :(得分:0)

为什么没有以下内容?

print.subject = function (x) {
    cat(x[[2]], '\n')
    invisible(x)
}

需要注意的两件事:

  1. NextMethod通常是一个好主意,但以上内容足够简单且健壮。相比之下,我什至不确定您的解决方案能做什么。
  2. 您需要使用[[而不是[子集来访问正确的列表元素(而不是列表切片)。

答案 1 :(得分:0)

无需首先将输出保存在列表中

import React from 'react';

export default class Blinker extends React.PureComponent {

    state = {
        message: 'This is side',
        side: 'A'
    };

    componentDidMount() {
        this.timerId = setInterval(() => this.tick(), 500);
    }

    tick = () => {
        let newSide;
        if (this.state.side === 'A') {
            newSide = 'B';
        } else {
            newSide = 'A';
        }
        this.setState({ side: newSide });
    };

    render() {
        return <span>{this.state.message} {this.state.side}</span>;
    }
}

输出

subject<-function(x,id) UseMethod("subject")
subject.LongitudinalData<- function(x ,id) { 
   a <- x[x$subjects==id,]
   class(a)<-c("subject","LongitudinalData","data.frame")
   invisible(a)
}


print.subject  <- function(x) {
  if(length(unique(x$subjects)) == 0) {
    noquote(paste("NULL"))
  } else {
      noquote(paste("Subject ID:",unique(x$subjects) ))
      }

}