对于此表,必须在不考虑NA的情况下为每个变量_T添加。
T1:
var1 var2 var3
Argentina Italy NA
Mexico Chile NA
France Hungary NA
Spain UK NA
我尝试了以下代码:
o_cols <- c("var1", "var2", "var3")
out_cols <- paste0(o_cols, "_T")
output <- data.table (data_base)
output[, c(out_cols) := lapply(.SD, function(x){paste0(x, "_T")}), .SDcols
= o_cols]
var_cols <- paste0(o_cols, "_value")
将包括“ NA”在内的所有变量都加_T的问题。
最终结果必须如下所示:
var1_value var2_value var3
Argentina_T Italy_T NA
Mexico_T Chile_T NA
France_T Hungary_T NA
Spain_T UK_T NA
答案 0 :(得分:1)
您可以轻松完成
df[!is.na(df)] <- paste0(df[!is.na(df)], '_T')
df
# var1 var2 var3
#1 Argentina_T Italy_T NA
#2 Mexico_T Chile_T NA
#3 France_T Hungary_T NA
#4 Spain_T UK_T NA
答案 1 :(得分:0)
几乎。您可以将ifelse()
添加到lapply()
中。
> result
var1_T1 var2_T1 var3_T1
1 Argentina_T1 Italy_T1 NA
2 Mexico_T1 Chile_T1 NA
3 France_T1 Hungary_T1 NA
4 Spain_T1 UK_T1 NA
# Paste each value as "value_T1" if it is not NA
result <- data.frame(lapply(df, function(x) ifelse(!is.na(x), paste0(x, "_T1"), x)),
stringsAsFactors = FALSE)
# Convert each column name to "name_T1"
colnames(result) <- paste0(colnames(result), "_T1")
df <- read.table(text = "var1 var2 var3
Argentina Italy NA
Mexico Chile NA
France Hungary NA
Spain UK NA", header = TRUE, as.is = TRUE)
悬而未决的问题:您要使用哪种逻辑类型转换列名?一个NA
是否足以不应用转换?要不是所有值都必须为NA
?
答案 2 :(得分:0)
一个constructor(props) {
super(props);
this.state = {
name: "",
search: "",
data: this.props.assetManagement
};
this.sortBy = this.sortBy.bind(this);
this.compareBy = this.compareBy.bind(this);
}
选项
data.table
数据
library(data.table)
DT <- fread(text)
for (nm in names(DT)) {
tmp <- paste0(DT[[nm]], "_T")
set(DT, i = which(!is.na(DT[[nm]])), j = nm, value = tmp)
}
DT
# var1 var2 var3
#1: Argentina_T Italy_T NA
#2: Mexico_T Chile_T NA
#3: France_T Hungary_T NA
#4: Spain_T UK_T NA