【发布时间】:2014-01-30 17:34:27
【问题描述】:
我很难调整我以前用来读入和重新编码顺序标记的 data.tables 的脚本。
我在 R 中有一系列按顺序标记的 data.tables:df1、df2、df3 等。然后,我应用了特定(且不一致的)规则来在其中创建新变量data.tables 称为 status 和 csat。
我想做的是:
- 读入数据表
- 将
csat变量重新编码为新变量 - 对 data.table 进行子集化,使其仅包含 4 个变量(
csat、csat_d、id和status) - 使用外连接将 data.table 与以前的表合并(因此可以将其重新整形为长格式)
我正在尝试解决以下脚本中的第 1-3 点,但不知道如何实现 #4。
已编辑:
df_names<-c(df,df2,df3) # Create list of data.tables csat_vars<-c("CustomerId","csat","csat_d","status") # Create list of 4 variables out <- lapply(1:length(df_names), function(idx) { d <- df_names[idx] d$csat_d <- recode(d$csat,"1:5=0;6:7=1;NA=NA;") d <- subset(d, select=c(csat_vars)) })
我不知道使用data.table 或data.frame 是否更好(这些是小型数据集),因此欢迎任何帮助。
这里的迷你数据集:
> dput(head(df))
structure(list(respid = c(1499L, 433L, 2600L, 2282L, 1503L, 3304L
), csat = c(4L, 6L, NA, NA, 6L, 4L), status = c("Active", "Active",
"Active", "Active", "Active", "Active"), touch = c(2L, 3L, 2L,
3L, 2L, 2L)), .Names = c("CustomerId", "csat", "status", "touch"), class = c("data.table",
"data.frame"), row.names = c(NA, -6L), .internal.selfref = <pointer: 0x7f800301b778>)
> dput(head(df2_r))
structure(list(respid = c(6L, 5L, 149L, 147L, 270L, 145L), csat = c(4L,
NA, 6L, 7L, 7L, 4L), status = c("Active", "Lapsed/Churned", "Active",
"Active", "Active", "Active"), touch = c(3L, NA, 3L, 1L, 3L,
1L)), .Names = c("CustomerId", "csat", "status", "touch"), class = c("data.table",
"data.frame"), row.names = c(NA, -6L), .internal.selfref = <pointer: 0x7f800301b778>)
> dput(head(df3))
structure(list(respid = c(1713L, 1611L, 1630L, 1773L, 1391L,
1571L), csat = c(4L, 6L, 4L, 5L, 7L, 4L), status = c("Active",
"Active", "Active", "Active", "Active", "Active"), AGENCY_1 = c(NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_
)), .Names = c("CustomerId", "csat", "status", "AGENCY_1"), class = c("data.table",
"data.frame"), row.names = c(NA, -6L), .internal.selfref = <pointer: 0x7f800301b778>)
【问题讨论】:
-
列出实际的
data.tables,而不是他们的名字,你有data.tables 还是data.frames?我之所以问,是因为您使用的是data.frame命名法来处理data.tables,即不使用:= -
他们是
data.tables,由于无知,我想我使用了错误的命名法:(请随时纠正我!先更改列表。
标签: r data.table