使用str_extract提取美元金额

时间:2019-06-11 17:16:58

标签: r stringr

我有一列文字,想用美元符号作为字符串的开头,仅提取字符串中包含的美元金额。我可以匹配美元符号,但不确定如何直接在数字后面加上数字(并删除逗号)。

我尝试使用美元符号作为str_extract的锚点,但并不仅获得全部美元金额。

input <- (c("the sum of $175,000,000 and the sum", "the sum of $20,000,000 and the sum", "the sum of $100,000,000 and the sum"))

df<-as.data.frame(input)

df %>% 
    mutate(amount = str_extract(input,"^\\$"))

在变种之前运行:

input
the sum of $175,000,000 and the sum
the sum of $20,000,000 and the sum
the sum of $100,000,000 and the sum

我希望它看起来像:

input                                         amount
the sum of $175,000,000 and the sum        175000000
the sum of $20,000,000 and the sum          20000000
the sum of $100,000,000 and the sum        100000000

3 个答案:

答案 0 :(得分:1)

使用tff.federated_computation中的帮助程序功能parse_number

readr

基本上,我们使用df %>% mutate(amount = parse_number(str_match(input,"\\$([0-9,.]+)")[,2])) 去除“ $”,然后将其余部分传递给str_match以使其成为数字。这也适用于“ $ 11.11”之类的值

您也可以使用基本功能parse_number而不是as.numeric(),但是我想如果您使用其他tidyverse软件包,我会建议使用它。

答案 1 :(得分:1)

这是一种方法:

public class NetworkStatusReceiver extends BroadcastReceiver
{
    private static final String TAG = BroadcastReceiver.class.getSimpleName();

    @Override
    public void onReceive( Context context, Intent intent )
    {
        if( intent.getAction().equals(
                        ConnectivityManager.CONNECTIVITY_ACTION ) )
        {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if(((cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)!=null)&&
                    (cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)) || 
                    ((cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)!=null)&&
                     (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED)))
            {
                                        // Perform some action with wifi connection


            }
            else
            {
                    // Perform some action without wifi connection

            }
        }
    }

答案 2 :(得分:0)

使用base R

gsub(",", "", sub(".*[$]([0-9,]+)\\s*.*", "\\1", input))
#[1] "175000000" "20000000"  "100000000"