从数据创建R矢量

时间:2017-06-01 23:49:21

标签: r

我试图弄清楚如何找到A,B,C,D等中包含哪些区域。例如,A包含540,300,330。而C包含区域330. / p>

我想将这些保存到矢量中,如A = [540,300,330]和C = [300],D = [540,330]

数据:

Area    A   B   C   D
540     Y           Y    
300     Y       Y
330     Y           Y

我在考虑使用summaryBy语句。但这并没有给我预期的结果。

 summaryBy(Area ~ A, FUN=(length))

3 个答案:

答案 0 :(得分:3)

您可以通过以下方式获取包含所需内容的list()对象:

lapply(dat[c("A","B","C","D")], function(x) dat$Area[x=="Y"] )
#$A
#[1] 540 300 330
#
#$B
#integer(0)
#
#$C
#[1] 300
#
#$D
#[1] 540 330

几乎没有理由填充单独的AB等变量。

如果你想要一个带有值和索引的'整洁的'2列数据帧,你可以在stack(...)中包含上述内容。

答案 1 :(得分:1)

使用<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <EditText android:id="@id/etUsername" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/pref_provider_title_user_name" android:ems="10"> <requestFocus /> </EditText> **<EditText android:id="@id/etPassword" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/pref_provider_title_user_password" android:ems="10" android:inputType="textPassword" />** <EditText android:id="@id/etServer" android:visibility="gone" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/pref_provider_title_server" android:ems="10" /> <TextView android:id="@id/tvInfo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ems="10" /> <Button android:id="@id/btnOk" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/text_ok" /> </LinearLayout> 更复杂:

tidyverse

Butif你有dat %>% gather(k,v,-Area) %>% filter(v=="Y") %>% nest(Area) %>% as.data.frame k data 1 A 540, 300, 330 2 C 300 3 D 540, 330 而不是空字符串,它几乎是优雅的:

NA

答案 2 :(得分:0)

以下是使用data.table

的选项
library(data.table)
dM <- melt(setDT(dat), id.var = "Area")[value == "Y"]
split(dM$Area, dM$variable)
#$A
#[1] 540 300 330

#$B
#integer(0)

#$C
#[1] 300

#$D
#[1] 540 330

如果我们需要data.frame或矩阵输出

`dim<-`(dat$Area[row(dat[-1]) *NA^(dat[-1]!="Y")], dim(dat[-1]))
#     [,1] [,2] [,3] [,4]
#[1,]  540   NA   NA  540
#[2,]  300   NA  300   NA
#[3,]  330   NA   NA  330