2016-11-11 38 views
1

我有一個數據框,其中包含由「。」分隔的數字和數字。我想改變依賴於「。」的條目。串。 如果條目不包含「。」應添加前綴「 - 」。使用子集或grep功能很簡單。但我也想替換包含「。」的條目。與「。」的櫃檯。R - 按特定字符串更改數據框條目(按計數器值更改數字並更改符號)

我的示例數據:

X1  X2 
1  2 
3  4 
6  8 
5  1.2 
3.4  7 
1.2.5 9 
11  3.4.7 

,我想有它看起來像這樣:

X1  X2 
-1  -2 
-3  -4 
-6  -8 
-5  1 
2  -7 
3  -9 
-11  4 

我不知道,並試圖早已子集化,提取「」部分來計算它們。但我無法插入櫃檯。謝謝你的幫助。

+0

因爲它是t他第三次和第四次是「。」出現 – Miguel123

+0

是的,我知道了。看看我的回答 – Sotos

+0

是的,謝謝! :)也是一個不錯的解決方案,雖然我不熟悉sapply。根據你的問題 - 如果我們想要檢查「。」的數字,代碼將如何顯示 - 條目並將其替換爲上面組合出現的行號?這意味着:1.2。 => 1,3.4 => 2,1.2.5 => 4,3.4.7 => 5? – Miguel123

回答

2

這裏是經由基礎R一個想法,

ind <- rowSums(sapply(df, function(i) cumsum(grepl('\\.', i)))) 
df[] <- lapply(df[], function(i) ifelse(grepl('\\.', i), ind, paste0('-', i))) 

df 
# X1 X2 
#1 -1 -2 
#2 -3 -4 
#3 -6 -8 
#4 -5 1 
#5 2 -7 
#6 3 -9 
#7 -11 4 

:我轉換df爲char ACTER,

df[] <- lapply(df[], as.character) 

編輯

關於你的行號的要求,那麼這應該這樣做,

ind1 <- apply(df, 1, function(i) paste(sort(i), collapse = '.')) 
df2 <- sapply(df, function(i) match(i, ind1)) 
df[] <- lapply(df[], function(i) ifelse(grepl('\\.', i), 0, paste0('-', i))) 
df[!is.na(df2)] <- df2[!is.na(df2)] 
df 
# X1 X2 
#1 -1 -2 
#2 -3 -4 
#3 -6 -8 
#4 -5 1 
#5 2 -7 
#6 4 -9 
#7 -11 5 

如果在以後用這個數據幀做計算的規劃,然後你應該轉換爲整數,即,

df[] <- lapply(df[], as.integer) 

str(df) 
#'data.frame': 7 obs. of 2 variables: 
# $ X1: int -1 -3 -6 -5 2 4 -11 
# $ X2: int -2 -4 -8 1 -7 -9 5 
0

這與data.table 的想法是建立在臨時列計數器:

library(data.table) 

dt<-data.table(df) 
dt$X1 <- as.character(dt$X1) 
dt$X2 <- as.character(dt$X2) 
dt[!grepl(".", dt$X1, fixed=TRUE),X1:=paste("-", X1, sep="") ] 
dt[!grepl(".", dt$X2, fixed=TRUE),X2:=paste("-", X2, sep="") ] 
dt[grepl(".", dt$X1, fixed=TRUE)|grepl(".", dt$X2, fixed=TRUE), count_point:=as.character(sequence(.N))] 
dt[grepl(".", dt$X1, fixed=TRUE),X1:=count_point] 
dt[grepl(".", dt$X2, fixed=TRUE),X2:=count_point] 
df <- data.frame(dt[, c("X1", "X2"), with = FALSE]) 

應該有辦法做到這一點在更短的線,採用.SD

+0

哇,這工作。從來沒有想過一個臨時專欄... – Miguel123