【问题标题】:Subsetting data frame in R based on specific indices of original dataframe基于原始数据帧的特定索引在 R 中对数据帧进行子集化
【发布时间】:2015-03-21 21:56:33
【问题描述】:

我想从原始dataframe 创建一个新的dataframe 对象,并希望通过选择与我的情况相关的索引来实现。假设我的dataframe 有一个名为subjectnumber 的变量,我想创建我的新dataframe,其中仅包括subjectnumber 属于此列表c(2,4,6,7,8) 的行。

简而言之,这就是我想要实现的:

new.dataframe <- subset(old.dataframe(for (old.dataframe$subjectnumber == c(2,4,6,7,8))))

【问题讨论】:

    标签: r dataframe subset


    【解决方案1】:

    假设 df 是您的旧数据框:

    new.df = df[df$subjectnumber %in %c(2,4,6,7,8),]
    

    示例:

    df = data.frame(col1=1:10, col2=letters[1:10])
    
    #   col1 col2
    #1     1    a
    #2     2    b
    #3     3    c
    #4     4    d
    #5     5    e
    #6     6    f
    #7     7    g
    #8     8    h
    #9     9    i
    #10   10    j
    
    df[df$col1 %in% c(2,3,6,10,8),]
    
    #   col1 col2
    #2     2    b
    #3     3    c
    #6     6    f
    #8     8    h
    #10   10    j
    

    【讨论】:

    • 谢谢!这正是我想要的!
    猜你喜欢
    • 2021-10-16
    • 1970-01-01
    • 2018-07-08
    • 2020-10-13
    • 2012-11-17
    • 2021-02-02
    • 2020-07-07
    • 2021-06-08
    • 2015-06-20
    相关资源
    最近更新 更多