R根据数据分配新变量

问题描述 投票:-1回答:2

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

这是我数据的一部分。

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个小时有租金,
  • 如果该租赁的用户名等于搜索的用户名

然后数据$ result < - “成功”

r loops if-statement
2个回答
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
    }
  }
}

它适用于您提供的小矩阵,但您需要尝试确保它与较大的矩阵一起正常工作。


1
投票

我更改了您的数据,因为它对您的说明没有意义。您拥有的时间变量是一个时间点而不是持续时间。所以你需要一个持续时间或两个点。您还说租用的用户名等于搜索的用户名,但您只提供了一个名称。无论你如何设置if else,如你所描述的那样。

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")
© www.soinside.com 2019 - 2024. All rights reserved.