2010-07-08 27 views
2

我正在使用R.以下面創建的數據集爲例。我希望能夠將ip除以".",同時將原始行信息保存在colorstatus中。我認識到這將創建一個更長的數據集,其中colorstatus的條目將重複其自身。R.在數據集的分割字符串中存在的難題,但在其他列中保留信息

a <- data.frame(cbind(color=c("yellow","red","blue","red"), 
     status=c("no","yes","yes","no"), 
     ip=c("162.131.58.26","2.131.58.16","2.2.58.10","162.131.58.17"))) 
+0

爲所有感興趣:這是丟失R標籤的老問題。 – Marek 2011-01-24 15:49:21

回答

0
a <- cbind(a[,1:2], t(matrix(as.numeric(unlist(strsplit(as.character(a[,3]), "\\."))), nrow = nrow(a), ncol = 4))) 

不知道這是否是你想要的,我敢肯定有一個更好看的方式來做到這一點,即使它是你想要的。

0
# give a an id to match cases 
a$id <- 1:nrow(a) 

# split the ip address and store in datab 
datab <- unlist(strsplit(as.character(a$ip),"\\.")) 

# put the parts of the ip address against the correct ids in a new dataframe 
datac <- data.frame(id=sort(rep(1:4,nrow(a))),ip=datab) 

# merge the data together, remove unwanted variables, correct column name 
final <- merge(datac,a,by="id") 
final <- final[c("ip.x","color","status")] 
colnames(final)[1] <- "ip" 

這會給你一個新的行上的IP地址的每個部分,顏色和狀態變量重複。我希望這是你以後的樣子。否則,以前的答案看起來像是一個很好的讓ip數據進入列而不是行。

3

不清楚OP是否需要新的行或列,所以這裏的兩個:

列:

library(reshape) 
a <- data.frame(a, colsplit(a$ip, split = "\\.", names = c("foo", "bar", "baz", "phi"))) 

或行(添加上面列後)

a.m <- melt(a, id.vars = c("color", "status", "ip")) 
相關問題