R根据数据分配新变量

时间:2019-03-14 08:40:07

标签: r loops if-statement

我有一个数据,其中包括租金和搜索量。如果搜索是由出租的同一客户进行的,并且如果在出租之前进行了搜索,那么我想指定为成功搜索。

这是我数据的一部分。

time <- c("2019-03-13 14:43:00", "2019-03-13 14:34:00", "2019-03-13 14:23:00")
user <- c("A", "B", "A")
Type <- c("Rental","Search","Search")
data <- cbind(time, user, Type)

我需要一个新列来显示第三行成功。

但是我有很多数据。所以我需要做这样的事情:

  • 如果类型是搜索,则
  • 如果在搜索后最多2个小时有租金,
  • 如果租金的用户名等于搜索的用户名

然后数据$结果<-“成功”

2 个答案:

答案 0 :(得分:1)

我更改了您的数据,因为它与您的说明无关。您拥有的时间变量是时间点而不是持续时间。因此,您需要一个持续时间或两点。此外,您还说租金的用户名等于搜索的用户名,但您只提供了一个名称。无论如何,您都会按照自己的描述设置if。

time <- c(1:3)
username <- c("A", "B", "A")
rentalname <- c("A", "B", "A")
Type <- c("Rental","Search","Search")
data <- data.frame(time, username, rentalname, Type)


data$result <- ifelse( 
    data$Type %in% "Search" & 
    data$time > 2 &
    data$username %in% data$rentalname, "Successful" ,"Failure")

答案 1 :(得分:0)

如果我很了解您想要什么,那么它应该可以工作(它将使用成功的条目创建新的数据框“成功”):

# create new data frame
success <- data.frame(time=character(), user=character(), Type=character(), result=character(), stringsAsFactors=F)

count <- 1

# loop around each user
for(us in unique(data[,"user"])){

  # subset data per user
  subdata <- data[data[,"user"] == us, ]

  # skips the user if there is only one entry for that user or if there is no "Rental" entry in "Type"
  if(is.null(dim(subdata))) next;
  if(!is.null(dim(subdata)) & !any(subdata[,"Type"] == "Rental")) next;

  # sort subdata chronologically
  subdata <- subdata[order(subdata[,"time"]),]

  # loop around rows in the subdata
  for(i in 2:nrow(subdata)){

    # calculate the time difference between entries i and i-1 if i is a rental and i-1 a search
    if(difftime(subdata[i,"time"], subdata[i-1, "time"], units="mins") < 120 & subdata[i-1, "Type"] == "Search" & subdata[i, "Type"] == "Rental"){
      success[count,] <- c(subdata[i,], "success")
      count <- count +1
    }
  }
}

它适用于您提供的那个小矩阵,尽管您需要尝试确保它适用于较大的矩阵。

相关问题