R脚本-循环期间更新DataFrame的值

问题描述 投票:0回答:2

我正在尝试在称为输入的数据帧上的R脚本中运行循环。并更新列名Valid。

function myFunction(x){
    Result <- x * 2 
return(Result)
}

for (row in nrow(input)){
input$Valid[row] == myFunction(2)
}



output <- input 

但未更新数据框。是的,我想循环执行此操作。

r rscript
2个回答
0
投票

for循环中有几个问题:

  1. [nrow(input)只是一个数字,因此您需要创建一个从1nrow(input)的范围,即seq_len(nrow(input))
  2. ==用于判断是否相等,因此,请使用<-=进行值分配

示例

for (row in seq_len(nrow(input))){
  input$Valid[row] <- myFunction(2)
}

0
投票

我能够根据您的建议进行处理:

这是我正在使用的完整脚本:它正在使用SOAP请求通过http://ec.europa.eu/taxation_customs/vies/checkVatService.wsd验证欧盟增值税号。>

VatCheck <- function(x,z)
{
get_config_proxy <- function(url, user = NULL, pwd = NULL, verbose = FALSE, auth = "basic") {
  # curl::ie_get_proxy_for_url wants a scheme - either way it don't work
  if(is.null(httr::parse_url(url)$scheme)) {
    if (verbose)  message("No scheme provided. assume HTTP")
    url <- modify_url(url, scheme = "http")
  }
  # get the proxy url if needed
  proxy_url <- curl::ie_get_proxy_for_url(url)
  # return blank config if no proxy required
  if(is.null(proxy_url)) {
    if(verbose) message("No proxy")
    return(httr::config())
  }
  if(verbose) message("Proxy found")
  # Otherwise configure the proxy / user and password are needed

  # return a config object for use with httr
  proxy_config <- httr::use_proxy(url = proxy_url, auth = auth)
}
body = sprintf("<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:urn='urn:ec.europa.eu:taxud:vies:services:checkVat:types'>  
   <soapenv:Body>
      <urn:checkVat xmlns='urn:ec.europa.eu:taxud:vies:services:checkVat:types'>
         <urn:countryCode>%s</urn:countryCode>
         <urn:vatNumber>%s</urn:vatNumber>
      </urn:checkVat>
   </soapenv:Body>
</soapenv:Envelope>",x,z)
url <- "http://ec.europa.eu/taxation_customs/vies/services/checkVatService"
# No proxy configured so we get a timeout from curl fetch
# req <- GET(url) 
# we configure the proxy giving interactively user and password
config_proxy <- get_config_proxy(url)
# we make a GET using the config
x <- with_config(config_proxy, POST(url, body=body))
req<-toString(content(x)) # we get 200. it works! 
req
 }



for(i in 1:nrow(input)) {
  input[i, "Valid"] <- VatCheck(x = toString(input[i, "Column1"])  , z= toString(input[i, "Colum2"]))   
}
output <- input 
© www.soinside.com 2019 - 2024. All rights reserved.