如果单个级别在t中有多个项目,如何从因子级别提取项目

时间:2019-06-04 07:33:42

标签: r

我的数据框中有一个列-FD,它是具有6个级别的因子,如下所示

级别:[1,4,5] [1,5] [1] [2,4] [2] [3,5]

,但是每个级别中都有多个元素。那么如何从各个级别提取/访问元素/项目

sample<-read.csv(file.choose(), header=T)
df<-as.data.frame(sample)
df

v<-df$Nodes[]

w<-df$FirstDegree[]
for (i in v) {
  t<-c(1:5)
  if (df$FirstDegree[t][2]==i){
    print(1)
    }
  else {
    print(0)
    }
  }

我需要创建一个带有1和0的矩阵,其中1表示所选节点值是否存在于FirstDegree中,否则为0。我正试图为此目的访问级别中的项目

1 个答案:

答案 0 :(得分:0)

我将因子转换为字符对象,然后检查字符串中是否存在1到5度。

假设这是您的数据

FirstDegree <- factor(c("[1, 4, 5]", "[1,5]", "[1]", "[2, 4]", "[2]", "[3, 5]"))
FirstDegree
Levels: [1, 4, 5] [1,5] [1] [2, 4] [2] [3, 5]

我会

FirstDegree <- as.character(FirstDegree)

# sapply runs the code below for every possible degree 1 to 5
m <- sapply(1:5, function(degreenumber){
# we convert the number 1 to 5 to a character and see if this number
# is present in the vector FirstDegree. grepl returns TRUE or FALSE but since
# you asked for 1 or 0 we use as.numeric
as.numeric(grepl(as.character(degreenumber), FirstDegree))})
# the resulting matrix looks like this:
m
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    0    1    1
[2,]    1    0    0    0    1
[3,]    1    0    0    0    0
[4,]    0    1    0    1    0
[5,]    0    1    0    0    0
[6,]    0    0    1    0    1